wordpress - 使用来自子主题而不是来自父主题的 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
解决方案
这里有几个问题
您应该将 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
}
谢谢!
推荐阅读
- c# - WPF c#如何在成功登录尝试后切换到仪表板视图?这是m代码
- python - 使用 Python 请求模块发送数据时出现转换值错误
- sql - SQL:根据最近的日期选择具有一个唯一字段的多个字段
- tensorflow - 在 Visual Studio 上使用 tensorflow-lite 时出错
- javascript - react-native 错误无法读取未定义的属性“拆分”
- informatica - 从 informatica 中的字符串中删除字符
- javascript - 页面滚动时,iPhone Safari 上不处理触摸事件
- javascript - Bootstrap Datatables Javascript - Lengthmenu 选项不起作用
- class - VBA 类实例化和范围
- php - WooCommerce 使用简码描述的特色产品