WordPress 插件开发 - 如何使用 JQuery / JavaScript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16823679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WordPress Plugin Development - How to use JQuery / JavaScript?
提问by JimmyJammed
Just started developing a plugin for WordPress, wanted to use some JQuery in the Plugin Admin interface.
刚开始为 WordPress 开发插件,想在插件管理界面中使用一些 JQuery。
How do I properly include and call JQuery?
如何正确包含和调用 JQuery?
For instance, on a normal HTML page I would just include the JQuery library, then call this script:
例如,在一个普通的 HTML 页面上,我只会包含 JQuery 库,然后调用这个脚本:
$(document).ready(function(){
alert('Hello World!');
});
How can I do this in a WordPress Plugin PHP file?
如何在 WordPress 插件 PHP 文件中执行此操作?
回答by adeneo
Firstly, you always have to use a no-conflict wrapper in Wordpress, so your code would look like :
首先,您必须始终在 Wordpress 中使用无冲突包装器,因此您的代码将如下所示:
jQuery(document).ready(function($){
alert('Hello World!');
});
Secondly, it's good practice to put your javascript in external files, and in a Wordpress plugin you would include those like this :
其次,将您的 javascript 放在外部文件中是一种很好的做法,在 Wordpress 插件中,您将包含以下内容:
wp_register_script( 'my_plugin_script', plugins_url('/my_plugin.js', __FILE__), array('jquery'));
wp_enqueue_script( 'my_plugin_script' );
This includes your script, and sets up jQuery as a dependency, so Wordpress will automatically load jQuery if it's not already loaded, making sure it's only loaded once, and that it's loaded before your plugins script.
这包括您的脚本,并将 jQuery 设置为依赖项,因此如果 jQuery 尚未加载,Wordpress 将自动加载它,确保它只加载一次,并且在您的插件脚本之前加载。
And if you only need the script on the admin pages, you can load it conditionally using Wordpress add_action handlers:
如果您只需要管理页面上的脚本,您可以使用 Wordpress add_action 处理程序有条件地加载它:
add_action( 'admin_menu', 'my_admin_plugin' );
function my_admin_plugin() {
wp_register_script( 'my_plugin_script', plugins_url('/my_plugin.js', __FILE__), array('jquery'));
wp_enqueue_script( 'my_plugin_script' );
// do admin stuff here
}
回答by pjehan
It is not recommended to be using your own jquery version.
不建议使用您自己的 jquery 版本。
WordPress includes its own version of jquery and many other similar JS files, which have all been rigorously tested with WP and many of the most common plugins. In order to provide the best compatibility and experience for our users, we ask that you not package your own (especially not an older version) and instead use wp_enqueue_script() to pull in WordPress's version.
WordPress 包含自己的 jquery 版本和许多其他类似的 JS 文件,这些文件都经过 WP 和许多最常见的插件的严格测试。为了给我们的用户提供最好的兼容性和体验,我们要求您不要打包自己的(尤其是不是旧版本),而是使用 wp_enqueue_script() 来拉入 WordPress 的版本。
So you should use this instead:
所以你应该改用这个:
wp_enqueue_script('jquery')