[英]How to add custom javascript in wordpress posts area?
如果您可以访问 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.