如何向 WordPress 添加一个简单的 jQuery 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11159860/
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
How do I add a simple jQuery script to WordPress?
提问by Citizen
I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I've got as far as loading jQuery in functions.php
file, but all of the guides out there are crappy because they assume you already have a ton of WordPress experience. For instance, they say that now that I'm loading jQuery through the functions.php
file, now all I have to do is load my jQuery.
我阅读了 Codex 和一些关于在 WordPress 中使用 jQuery 的博客文章,这非常令人沮丧。我已经在functions.php
文件中加载 jQuery ,但是所有的指南都很糟糕,因为他们假设您已经拥有大量的 WordPress 经验。例如,他们说现在我正在通过functions.php
文件加载 jQuery ,现在我要做的就是加载我的 jQuery。
How exactly do I do this? What files, specifically, do I add code to? How exactly do I add it for a single WordPress page?
我该怎么做?具体来说,我应该向哪些文件添加代码?我究竟如何为单个 WordPress 页面添加它?
回答by kdev
I know what you mean about the tutorials. Here's how I do it:
我知道你对教程的意思。这是我的方法:
First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script>
tags in a .js file).
首先,您需要编写脚本。在您的主题文件夹中创建一个名为“js”的文件夹。在该文件夹中为您的 javascript 创建一个文件。例如你的script.js。将您的 jQuery 脚本添加到该文件(您不需要<script>
.js 文件中的标签)。
Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:
以下是您的 jQuery 脚本(在 wp-content/themes/your-theme/js/your-scrript.js 中)的外观示例:
jQuery(document).ready(function($) {
$('#nav a').last().addClass('last');
})
Notice that I use jQuery and not $ at the start of the function.
请注意,我在函数的开头使用了 jQuery 而不是 $。
Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script()
function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:
好的,现在打开主题的functions.php 文件。您将需要使用该wp_enqueue_script()
函数,以便您可以添加脚本,同时告诉 WordPress 它依赖于 jQuery。以下是如何做到这一点:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.
假设您的主题在正确的位置有 wp_head 和 wp_footer,这应该可以工作。如果您需要更多帮助,请告诉我。
WordPress questions can be asked over at WordPress Answers.
WordPress 问题可以在WordPress Answers 上提问。
回答by Stan
After much searching, I finallyfound something that works with the latest WordPress. Here are the steps to follow:
经过多次搜索,我终于找到了适用于最新 WordPress 的东西。以下是要遵循的步骤:
- Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
- Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
Make sure your custom jQuery .js looks like this:
(function($) { $(document).ready(function() { $('.your-class').addClass('do-my-bidding'); }) })(jQuery);
Go to the theme's directory, open up functions.php
Add some code near the top that looks like this:
//this goes in functions.php near the top function my_scripts_method() { // register your script location, dependencies and version wp_register_script('custom_script', get_template_directory_uri() . '/custom_js/jquery_test.js', array('jquery'), '1.0' ); // enqueue the script wp_enqueue_script('custom_script'); } add_action('wp_enqueue_scripts', 'my_scripts_method');
- Check out your site to make sure it works!
- 找到您的主题目录,在您的自定义 js 目录中创建一个文件夹(在本例中为custom_js)。
- 将您的自定义 jQuery 放在此目录中的 .js 文件中(在本例中为 jquery_test.js)。
确保您的自定义 jQuery .js 如下所示:
(function($) { $(document).ready(function() { $('.your-class').addClass('do-my-bidding'); }) })(jQuery);
进入主题目录,打开functions.php
在顶部附近添加一些代码,如下所示:
//this goes in functions.php near the top function my_scripts_method() { // register your script location, dependencies and version wp_register_script('custom_script', get_template_directory_uri() . '/custom_js/jquery_test.js', array('jquery'), '1.0' ); // enqueue the script wp_enqueue_script('custom_script'); } add_action('wp_enqueue_scripts', 'my_scripts_method');
- 检查您的网站以确保它有效!
回答by DibaCode
If you use wordpress child themefor add scripts to your theme, you should change the get_template_directory_uri function to get_stylesheet_directory_uri, for example :
如果您使用 wordpress子主题向主题添加脚本,则应将 get_template_directory_uri 函数更改为 get_stylesheet_directory_uri,例如:
Parent Theme :
父主题:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script(
'parent-theme-script',
get_template_directory_uri() . '/js/your-script.js',
array('jquery')
);
wp_enqueue_script('parent-theme-script');
}
Child Theme :
儿童主题:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script(
'child-theme-script',
get_stylesheet_directory_uri() . '/js/your-script.js',
array('jquery')
);
wp_enqueue_script('child-theme-script');
}
get_template_directory_uri : /your-site/wp-content/themes/parent-theme
get_template_directory_uri : /your-site/wp-content/themes/ parent-theme
get_stylesheet_directory_uri : /your-site/wp-content/themes/child-theme
get_stylesheet_directory_uri : /your-site/wp-content/themes/ child-theme
回答by Jitendra Damor
You can add jQuery or javascript in theme's function.php file. The code is as below :
您可以在主题的 function.php 文件中添加 jQuery 或 javascript。代码如下:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your_script_name', // your script unique name
get_template_directory_uri().'/js/your-script.js', //script file location
array('jquery') //lists the scripts upon which your script depends
);
}
For more detail visit this tutorial : http://www.codecanal.com/add-simple-jquery-script-wordpress/
有关更多详细信息,请访问本教程:http: //www.codecanal.com/add-simple-jquery-script-wordpress/
回答by josh.chavanne
Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever. You just need to make sure the path is correct. I suggest using something like this (assuming you are in your theme's directory).
除了通过函数放入脚本之外,您还可以“仅”在页眉、页脚、任何模板中的任何模板中包含一个链接(即链接 rel 标记)。您只需要确保路径正确即可。我建议使用这样的东西(假设你在你的主题目录中)。
<script type="javascript" href="<?php echo get_template_directory_uri();?>/your-file.js"></script>
A good practice is to include this right before the closing body tag or at least just prior to your footer. You can also use php includes, or several other methods of pulling this file in.
一个好的做法是在结束正文标签之前或至少在您的页脚之前包含它。您还可以使用 php 包含,或其他几种拉入此文件的方法。
<script type="javascript"><?php include('your-file.js');?></script>
回答by sameeuor
You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/
您可以使用此插件添加自定义 javascript 或 jquery。
https://wordpress.org/plugins/custom-javascript-editor/
When you use jQuery don't forget use jquery noconflict mode
使用 jQuery 时不要忘记使用 jquery noconflict 模式
回答by Ahmed Elcheikh
Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/
从这里回答:https: //premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/
Despite the fact WordPress has been around for a while, and the method of adding scripts to themes and plugins has been the same for years, there is still some confusion around how exactly you're supposed to add scripts. So let's clear it up.
Since jQuery is still the most commonly used Javascript framework, let's take a look at how you can add a simple script to your theme or plugin.
jQuery's Compatibility Mode
Before we start attaching scripts to WordPress, let's look at jQuery's compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress' jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.
What this boils down to is that you can't use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. Take a look at the code below to see what I mean:
尽管事实上 WordPress 已经存在了一段时间,并且向主题和插件添加脚本的方法多年来一直是一样的,但对于应该如何添加脚本仍然存在一些困惑。所以让我们把它弄清楚。
由于 jQuery 仍然是最常用的 Javascript 框架,让我们来看看如何向主题或插件添加简单的脚本。
jQuery 的兼容模式
在我们开始将脚本附加到 WordPress 之前,让我们先看看 jQuery 的兼容模式。WordPress 预先打包了一份 jQuery,您应该将其与您的代码一起使用。当WordPress的jQuery加载时,它使用兼容模式,这是一种避免与其他语言库冲突的机制。
这归结为您不能像在其他项目中那样直接使用美元符号。为 WordPress 编写 jQuery 时,您需要改用 jQuery。看看下面的代码,看看我的意思:
回答by Rob
There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.
这里有很多教程和答案,如何添加要包含在页面中的脚本。但是我找不到的是如何构造该代码以使其正常工作。这是因为 $ 没有在这种形式的 JQuery 中使用。
So here is my code and you can use that as a template.
所以这是我的代码,您可以将其用作模板。
jQuery(document).ready(function( $ ){
$("#btnCalculate").click(function () {
var val1 = $(".visits").val();
var val2 = $(".collection").val();
var val3 = $(".percent").val();
var val4 = $(".expired").val();
var val5 = $(".payer").val();
var val6 = $(".deductible").val();
var result = val1 * (val3 / 100) * 10 * 0.25;
var result2 = val1 * val2 * (val4 / 100) * 0.2;
var result3 = val1 * val2 * (val5 / 100) * 0.2;
var result4 = val1 * val2 * (val6 / 100) * 0.1;
var val7 = $(".pverify").val();
var result5 = result + result2 + result3 + result4 - val7;
var result6 = result5 * 12;
$("#result").val("$" + result);
$("#result2").val("$" + result2);
$("#result3").val("$" + result3);
$("#result4").val("$" + result4);
$("#result5").val("$" + result5);
$("#result6").val("$" + result6);
});
});
回答by Rajan471
**#Method 1:**Try to put your jquery code in a separate js file.
**#方法1:**尝试将您的jquery 代码放在单独的js 文件中。
Now register that script in functions.php file.
现在在functions.php 文件中注册该脚本。
function add_my_script() {
wp_enqueue_script(
'custom-script', get_template_directory_uri() . '/js/your-script-name.js',
array('jquery')
);
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
Now you are done.
现在你完成了。
Registering script in functions has it benefits as it comes in <head>
section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.
在函数中注册脚本有好处,因为它在<head>
页面加载时进入部分,因此它始终是 header.php 的一部分。因此,您不必每次编写新的 html 内容时都重复您的代码。
#Method 2:put the script code inside the page body under <script>
tag. Then you don't have to register it in functions.
#方法二:将脚本代码放在页面主体内的<script>
标签下。然后你不必在函数中注册它。
回答by Nigel Redmon
The solutions I've seen are from the perspective of adding javascript features to a theme. However, the OP asked, specifically, "How exactly do I add it for a singleWordPress page?" This sounds like it might be how I use javascript in my Wordpress blog, where individual posts may have different javascript-powered "widgets". For instance, a post might let the user change variables (sliders, checkboxes, text input fields), and plots or lists the results.
我所看到的解决方案是从将 javascript 功能添加到主题的角度来看的。但是,OP 特别询问,“我究竟如何为单个WordPress 页面添加它?” 这听起来可能是我在我的 Wordpress 博客中使用 javascript 的方式,其中各个帖子可能具有不同的 javascript 驱动的“小部件”。例如,帖子可能让用户更改变量(滑块、复选框、文本输入字段),并绘制或列出结果。
Starting from the JavaScript perspective:
从 JavaScript 的角度出发:
- Write your JavaScript functions in a separate “.js” file
- 在单独的“.js”文件中编写 JavaScript 函数
Don't even think about including significant JavaScript in your post's html—create a JavaScript file, or files, with your code.
甚至不要考虑在帖子的 html 中包含重要的 JavaScript — 使用您的代码创建一个或多个 JavaScript 文件。
- Interface your JavaScript with your post's html
- 将您的 JavaScript 与您帖子的 html 连接起来
If your JavaScript widget interacts with html controls and fields, you'll need to understand how to query and set those elements from JavaScript, and also how to let UI elements call your JavaScript functions. Here are a couple of examples; first, from JavaScript:
如果您的 JavaScript 小部件与 html 控件和字段交互,您需要了解如何从 JavaScript 查询和设置这些元素,以及如何让 UI 元素调用您的 JavaScript 函数。这里有几个例子;首先,来自 JavaScript:
var val = document.getElementById(“AM_Freq_A_3”).value;
And from html:
从 html:
<input type="range" id="AM_Freq_A_3" class="freqSlider" min="0" max="1000" value="0" oninput='sliderChanged_AM_widget(this);'/>
- Use jQuery to call your JavaScript widget's initialization function
- 使用 jQuery 调用 JavaScript 小部件的初始化函数
Add this to your .js file, using the name of your function that configures and draws your JavaScript widget when the page is ready for it:
将它添加到您的 .js 文件中,使用您在页面准备好时配置和绘制 JavaScript 小部件的函数的名称:
jQuery(document).ready(function( $ ) {
your_init_function();
});
- In your post's html code, load the scripts needed for your post
- 在帖子的 html 代码中,加载帖子所需的脚本
In the Wordpress code editor, I typically specify the scripts at the end of the post. For instance, I have a scripts folder in my main directory. Inside I have a utilities directory with common JavaScript that some of my posts may share—in this case some of my own math utility function and the flotr2 plotting library. I find it more convenient to group the post-specific JavaScript in another directory, with subdirectories based on date instead of using the media manager, for instance.
在 Wordpress 代码编辑器中,我通常会在文章末尾指定脚本。例如,我的主目录中有一个脚本文件夹。在里面,我有一个带有通用 JavaScript 的实用程序目录,我的一些帖子可能会共享它——在这种情况下,我自己的一些数学实用程序函数和 flotr2 绘图库。我发现将特定于帖子的 JavaScript 分组到另一个目录中更方便,例如,使用基于日期的子目录而不是使用媒体管理器。
<script type="text/javascript" src="/scripts/utils/flotr2.min.js"></script>
<script type="text/javascript" src="/scripts/utils/math.min.js"></script>
<script type="text/javascript" src="/scripts/widgets/20161207/FreqRes.js"></script>
- Enqueue jQuery
- 入队 jQuery
Wordpress registers jQuery, but it isn't available unless you tell Wordpress you need it, by enqueuing it. If you don't, the jQuery command will fail. Many sources tell you how to add this command to your functions.php, but assume you know some other important details.
Wordpress 注册了 jQuery,但它不可用,除非你通过排队告诉 Wordpress 你需要它。如果不这样做,jQuery 命令将失败。许多来源告诉您如何将此命令添加到您的functions.php,但假设您知道其他一些重要细节。
First, it's a bad idea to edit a theme—any future update of the theme will wipe out your changes. Make a child theme. Here's how:
首先,编辑主题是个坏主意——主题的任何未来更新都会抹去您所做的更改。制作儿童主题。就是这样:
https://developer.wordpress.org/themes/advanced-topics/child-themes/
https://developer.wordpress.org/themes/advanced-topics/child-themes/
The child's functions.php file does not override the parent theme's file of the same name, it adds to it. The child-themes tutorial suggest how to enqueue the parent and child style.css file. We can simply add another line to that function to also enqueue jQuery. Here's my entire functions.php file for the child theme:
孩子的functions.php 文件不会覆盖父主题的同名文件,而是添加到其中。child-themes 教程建议如何将父和子 style.css 文件排入队列。我们可以简单地向该函数添加另一行,也可以将 jQuery 加入队列。这是我的子主题的整个functions.php文件:
<?php
add_action( 'wp_enqueue_scripts', 'earlevel_scripts_enqueue' );
function earlevel_scripts_enqueue() {
// styles
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
// posts with js widgets need jquery
wp_enqueue_script('jquery');
}