【问题标题】:Adding jquery and custom scripts to a Wordpress theme将 jquery 和自定义脚本添加到 Wordpress 主题
【发布时间】:2013-02-13 22:13:54
【问题描述】:

通过 Google 进行一些搜索,我一遍又一遍地遇到相同的代码,用于将 jQuery 添加到从头开始的 Wordpress 主题中。

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 文件:

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

当我刷新我的 WP 网站时,似乎没有调用 theme.js 文件。在 Chrome 开发工具中,它没有列在正在渲染的 js 文件中。

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

【问题讨论】:

    标签: jquery wordpress wordpress-theming


    【解决方案1】:

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

    其次,只取消注册默认的 jQuery(与 WP 捆绑)if you really know what you are doing。在您的示例中,您正在从 Google 加载一个过时的版本(当前是 1.8.3,而不是 1.7.1)。另见:Don’t Dequeue WordPress’ jQuery

    第三,您应该使用get_stylesheet_directory_uri,这是对父主题文件夹和子主题文件夹计数的正确函数。

    最后,这段代码在/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 代码应该像这样封装:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多