繁体   English   中英

如何在wordpress帖子区域添加自定义javascript?

[英]How to add custom javascript in wordpress posts area?

我想在 WordPress 中添加一个 JavaScript 测验。 我已经尝试过使用这种方法以 HTML 方式使用它。 但它不工作。

是这个java脚本测验链接。

如果您可以访问 wordpress 模板,则可以使用简单的短代码。 例如使用以下代码(注解测试):

class MyShortCodes {
    public function __construct() {
        $this->init();
    }

    public function init() {
        add_shortcode('my_javascript', array($this, 'my_javascript'));
        add_shortcode('my_javascript_file', array($this, 'my_javascript_file'));
    }

    public function my_javascript($attributes, $content = null) {
        return ''; // REPLACE THIS BY YOUR JAVASCRIPT CODE.
    }

    public function my_javascript_file($attributes, $content = null) {
        // Except for pasting all the JavaScript into the post's content,
        // enqueue the JavaScript file here and only add a call to it in the
        // post's content above.
        wp_enqueue_script('my_javascript_file', get_bloginfo('template_directory') . '/js/my_javascript_file.js');
    }
}

new MyShortCodes();

将此文件放在 wordpress 模板的include目录中,并将其包含在functions.php

require_once 'includes/my_shortcodes.php';

如您所见,有两个选项:您可以通过调用[my_javascript]短代码(并编辑my_javascript函数以包含所有代码)将完整的 JavaScript 代码粘贴到帖子正文中,或者您可以将 JavaScript 加入my_javascript文件(例如quiz.js在模板)含有代码封装为一个对象或使用函数[my_javascript_file]将然后被包括一次,即使将显示更多内容),并且仅包括小的JavaScript代码段中的每个交通过[my_javascript]具有简单的调用中提供的功能quiz.js )。

还可以简短地查看短代码文档: https ://codex.wordpress.org/Shortcode_API。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM