如何正确地将jQuery加载到WordPress中 [英] How to load jQuery into WordPress properly

查看:111
本文介绍了如何正确地将jQuery加载到WordPress中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WordPress网站,我想使用一个名为DataTables的jQuery插件。我一直在努力找出将jQuery脚本和DataTables脚本加载到WordPress的正确方法。

I have a WordPress site that I would like to use a jQuery plugin called DataTables. I've been having troubling figuring out the right way to load the jQuery script and the DataTables script into WordPress.

我知道我应该使用以下内容: wp_enqueue_script(jquery) - 但我不知道放在哪里或如何加载我需要的其他jQuery插件。

I know I'm supposed to use something with: wp_enqueue_script("jquery") - but I do not know where to put it or how to load the other jQuery plugin i need.

我试过的最后一点是把它放在我的WordPress网站的 header.php 文件中:

The last bit I tried was putting this in the header.php file for my WordPress site:

<?php wp_enqueue_script("jquery"); ?>

<?php wp_head(); ?>

任何帮助都将不胜感激!

Any help would be greatly appreciated!

推荐答案

jQuery包含在WordPress核心中,当你包含你的javascript时,你可以声明你的脚本依赖于jquery被加载为wp_enqueue_script的第三个参数: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

jQuery is included in WordPress core and when you include your javascript, you can declare that your script is dependent on jquery being loaded as the third parameter of wp_enqueue_script: http://codex.wordpress.org/Function_Reference/wp_enqueue_script.

使用wp_enqueue_script的正确方法是将其包含在附加到特定操作挂钩的回调中。当我开始使用WordPress时,这对我来说听起来非常复杂,但它实际上是一个非常好的系统,因为它允许您在WordPress初始化期间运行代码时指定

The proper way to use wp_enqueue_script is to include it in a callback that is attached to a specific action hook. That sounded incredibly complicated to me when I started with WordPress, but it's actually a really good system because it allows you to specify when your code should run during the initialization of WordPress.

因此,在你的 functions.php 或插件中,你可以添加你的钩子。

So, in your functions.php or a plugin, you add your hook.

add_action( 'wp_enqueue_scripts', 'my_js_include_function' );

然后,在该函数中,运行实际包含,并声明您的脚本依赖于jquery 。

Then, in that function, you running the actual inclusion, and declare that your script is dependent on jquery.

function my_js_include_function() {
    wp_enqueue_script( 'my_script.js', '/path/to/myscript.js', array('jquery') );
}

wp_ennqueue_script()的第一个参数是您指定给您的任意名称脚本。如果您要声明另一个脚本依赖于原始脚本,那么您将在第三个参数中引用它。

The first parameter of wp_ennqueue_script() is an arbitrary name you are assigning to your script. If you were to then declare another script was dependent on the original one, that's how you would refer to it in the third parameter.

这篇关于如何正确地将jQuery加载到WordPress中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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