WordPress插件开发 - 如何使用JQuery / JavaScript? [英] WordPress Plugin Development - How to use JQuery / JavaScript?

查看:73
本文介绍了WordPress插件开发 - 如何使用JQuery / JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始为WordPress开发插件,想在插件管理界面中使用一些JQuery。

Just started developing a plugin for WordPress, wanted to use some JQuery in the Plugin Admin interface.

如何正确包含和调用JQuery?

How do I properly include and call JQuery?

例如,在普通的HTML页面上,我只包含JQuery库,然后调用此脚本:

For instance, on a normal HTML page I would just include the JQuery library, then call this script:

$(document).ready(function(){
    alert('Hello World!');
});

如何在WordPress插件PHP文件中执行此操作?

How can I do this in a WordPress Plugin PHP file?

推荐答案

首先,你总是必须在Wordpress中使用无冲突的包装器,所以你的代码看起来像:

Firstly, you always have to use a no-conflict wrapper in Wordpress, so your code would look like :

jQuery(document).ready(function($){
    alert('Hello World!');
});

其次,将javascript放在外部文件中是个好习惯,而在Wordpress插件中则包含这样的人:

Secondly, it's good practice to put your javascript in external files, and in a Wordpress plugin you would include those like this :

wp_register_script( 'my_plugin_script', plugins_url('/my_plugin.js', __FILE__), array('jquery'));

wp_enqueue_script( 'my_plugin_script' );

这包括你的脚本,并将jQuery设置为依赖项,因此如果是的话,Wordpress会自动加载jQuery尚未加载,确保它只加载一次,并在插件脚本之前加载。

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.

如果你只需要管理页面上的脚本,你可以加载它有条件地使用Wordpress add_action处理程序:

And if you only need the script on the admin pages, you can load it conditionally using Wordpress add_action handlers:

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
}

这篇关于WordPress插件开发 - 如何使用JQuery / JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆