首页 > 解决方案 > 使用来自子主题而不是来自父主题的 JS 文件

问题描述

我正在尝试加载init.js从子主题加载并从父主题中卸载一个。

结果是我现在在两个文件的页面样式上都看到了。为什么没有卸载父文件,我该如何卸载它?

我已经添加了/child-theme/function.php这个

add_action( 'wp_enqueue_scripts', 'wpshout_dequeue_and_then_enqueue', 100 );

function wpshout_dequeue_and_then_enqueue() {
    // Dequeue (remove) parent theme script
    wp_dequeue_script( '/js/init.js' );

    // Enqueue replacement child theme script
    wp_enqueue_script(
        'modified_child_script',
        get_stylesheet_directory_uri() . '/js/init.js',
        array( 'jquery' )
    );
}

这两个文件具有相同的名称,并且位于

parent-theme
-js/init.js

child-theme
-js/init.js

标签: wordpress

解决方案


这里有几个问题

  • 您应该将 get_stylesheet_directory_uri() 用于子主题,将 get_template_directory_uri() 用于父主题,而不是 get_bloginfo() 函数。后者速度较慢,使用前两个函数

  • 脚本和样式应该被注销并出列以将它们完全从队列中删除

  • 优先级很重要。您需要稍后挂钩您的函数,以确保在取消注册之前已注册样式和脚本,否则它将无法工作。

解决方案:

将父 js 文件复制到您的子主题并打开它并进行必要的更改。保存文件

现在您需要将父 js 文件出列并取消注册,然后将新的子主题 js 文件入队

add_action( 'wp_enqueue_scripts', 'wpshout_dequeue_and_then_enqueue', 100 );

function wpshout_dequeue_and_then_enqueue() {
    wp_dequeue_script( 'parent-script-handle' );
    wp_deregister_script( 'parent-script-handle' );
    // Now the parent script is completely removed

    /*
     * Now enqueue you child js file, no need to register if you are not 
     * doing conditional loading
     */
    wp_enqueue_script( 'child-script-handle', get_stylesheet_directory_uri() . '/js/init.js' );
    //Now we have done it correctly
}

谢谢!


推荐阅读