【问题标题】:Overriding parent theme javascript from child theme从子主题覆盖父主题javascript
【发布时间】:2014-08-17 07:53:33
【问题描述】:

我的父主题在 \includes\js\custom.js 中有一个脚本,我正试图从我的子主题中覆盖它。我可以从我的父主题中看到它是使用此代码排队的:(我已经修剪了一些不相关的 wp_enqueue_script() 调用行。)

function my_deregister_scripts() {
        wp_deregister_script( 'jquery' );
        wp_enqueue_script('jquery', get_template_directory_uri().'/includes/js/jquery.min.js', false, '1.6.4');
        wp_enqueue_script('jquery-custom', get_template_directory_uri().'/includes/js/custom.js', false, '1.0');
        if ( is_singular() && get_option('thread_comments') ) wp_enqueue_script( 'comment-reply' );
}

起初,我想我可以像这样简单地将一些代码添加到我自己的子functions.php中:

function custom_script_fix()
{
    wp_dequeue_script( 'jquery-custom' );
    wp_enqueue_script( 'child-jquery-custom', get_stylesheet_directory_uri() .'/includes/js/custom.js', false, '1.0');
}
add_action( 'wp_enqueue_scripts', 'custom_script_fix' );

但后来我在法典中读到,如今,子functions.php 在父functions.php 之前立即运行。这意味着我正在使将在父functions.php中再次入队的东西出队。这导致我的脚本首先被加载,然后是父脚本:

那么,在不以任何方式修改父主题的情况下,我将如何做到这一点?

【问题讨论】:

标签: javascript php wordpress themes customization


【解决方案1】:

通过简单地注册脚本并使用父主题中使用的相同句柄,它具有优先权。因此,当父主题开始将自己的版本加入队列时,句柄已经分配,​​而是将覆盖加入队列。

function custom_script_fix()
{
    // use same handle as parent theme to override ('jquery-custom')
    wp_register_script('jquery-custom', get_stylesheet_directory_uri() .'/includes/js/custom.js', false, '1.0');
}

add_action( 'wp_enqueue_scripts', 'custom_script_fix' );

wp_enqueue_script() 上的描述指定它不会替换注册版本。您可能需要在add_action() 上设置较低的$priority,以确保首先注册您的覆盖脚本。

【讨论】:

  • 我发现单独使用wp_register_script() 就足够了,因为以后调用它或wp_register_script() 不会取代覆盖。这也意味着任何以这种方式覆盖的脚本只有在原始脚本被包含的情况下才会被包含在内。
  • @Walf 解决方案对我来说也足够了
猜你喜欢
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
相关资源
最近更新 更多