将jquery和自定义脚本添加到Wordpress主题 [英] Adding jquery and custom scripts to a Wordpress theme

查看:103
本文介绍了将jquery和自定义脚本添加到Wordpress主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过Google进行搜索时,我一遍又一遍地遇到了相同的代码,它们将jQuery添加到一个从零开始的Wordpress主题中.

Doing some searching through Google, I came across the same bit of code over and over for adding jQuery to a from-scratch Wordpress theme.

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
   wp_enqueue_script('my_script', get_bloginfo('template_url') . '/js/theme.js', array('jquery'), '1.0', true);
}

我已将此代码添加到我的functions.php文件中,并使用以下语法在其中创建了一个js文件夹并创建了theme.js文件:

I've added this code to my functions.php file, and I created a js folder and made a theme.js file using the following syntax in it:

jQuery(function ($) {
    /* You can safely use $ in this code block to reference jQuery */
});

当我刷新WP网站时,似乎没有调用theme.js文件.在Chrome开发工具中,未在要呈现的js文件中列出该文件.

When I refresh my WP site, the theme.js file doesn't seem to be called. In Chrome Dev tools, it's not listed among the js files being rendered.

我使用的是过时的方法吗?如何使用jquery使/js/theme.js文件适合我的主题?

Am I using an outdated approach? How can I make my /js/theme.js file, using jquery, work for my theme?

推荐答案

首先, 仅在前端运行,因此不需要is_admin()检查.

第二,仅注销默认的jQuery(与WP捆绑在一起)不要让WordPress的jQuery出队

Second, only de-register the default jQuery (bundled with WP) if you really know what you are doing. In your example, you are loading an outdated version from Google (current is 1.8.3, not 1.7.1). Also, see: Don’t Dequeue WordPress’ jQuery

第三,您应该使用 get_stylesheet_directory_uri ,这是将适用于父主题文件夹和子主题文件夹的正确功能.

Third, you should be using get_stylesheet_directory_uri, which is the correct function that will count for parent and child theme folders.

最后,此代码在/themes/my-theme/functions.php中可以正常工作:

Finally, this code works ok in /themes/my-theme/functions.php:

add_action( "wp_enqueue_scripts", "my_js_so_14864221", 11 );

function my_js_so_14864221() 
{
    wp_enqueue_script( 
        'my_script', 
        get_stylesheet_directory_uri() . '/js/theme.js', 
        array( 'jquery' ), 
        '1.0', 
        true
    );
}

并且您的theme.js中的jQuery代码应封装为:

And your jQuery code in theme.js should be encapsulated like:

jQuery(document).ready(function($) {   
    // $('#your-stuff').animate().hide().whatever();
});

这篇关于将jquery和自定义脚本添加到Wordpress主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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