javascript - 从子主题覆盖父主题javascript

标签 javascript php wordpress themes customization

我的父主题在\includes\js\custom.js 中有一个脚本,我正试图从我的子主题中覆盖它。我可以从我的父主题中看到它是使用此代码排队的:(我已经 trim 了一些不相关的 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 中再次入队。这导致我的脚本首先被加载,然后是父脚本:

As you can see, the child script loads, then the parent.

那么,在不以任何方式修改父主题的情况下,我该怎么做呢?

最佳答案

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

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以确保首先注册您的覆盖脚本。

关于javascript - 从子主题覆盖父主题javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430903/

相关文章:

javascript - 无法从 jquery ajax 向 php 发送数据?

css - Wordpress - 在主页上更改视频 (iframe) 尺寸

javascript - 如何检查至少一个复选框被选中

javascript - 具有多个异步操作的 Extjs Promise

javascript - html5视频播放器与视频js的关系

php - WooCommerce - 从我的帐户页面的菜单中删除下载

WordPress 网站显示 "Index of/"

javascript - 如何使大型 if/else 语句更紧凑?

php - 这里需要一点关于 php 的帮助

php - 在jquery中下载pdf文件