如何向WordPress添加简单jQuery脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何向WordPress添加简单jQuery脚本相关的知识,希望对你有一定的参考价值。

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 tags in a .js file).

Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:

jQuery(document).ready(function($) {
$('#nav a').last().addClass('last');
})

Notice that I use jQuery and not $ at the start of the function.

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:

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
);
}
  1. jQuery(document).ready(function($) {
  2. $('#nav a').last().addClass('last');
  3. })
  4.  
  5. ------
  6.  
  7. add_action( 'wp_enqueue_scripts', 'add_my_script' );
  8. function add_my_script() {
  9. wp_enqueue_script(
  10. 'your-script', // name your script so that you can attach other scripts and de-register, etc.
  11. get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
  12. array('jquery') // this array lists the scripts upon which your script depends
  13. );
  14. }

以上是关于如何向WordPress添加简单jQuery脚本的主要内容,如果未能解决你的问题,请参考以下文章

如何将此 jQuery 脚本添加到我的 Wordpress

如何将自定义 javascript 添加到 WordPress 管理员?

在 Wordpress 内联脚本中使用 jQuery

如何在 WordPress 管理员上运行 jQuery 代码?

jQuery 和 Wordpress

如何阻止 jQuery ajax 向 JSON 字符串添加斜杠?