在典型的WordPress的流动,插件是加载在主题之前,并且在子主题的情况下,在父主题之前加载子主题,具体而言,functions.php
子主题的文件被包括在父类的functions.php之前。因此,wp_enqueue_scripts
动作堆叠起来,然后按照该顺序执行,除非动作的优先级被定义为不同于默认值(10)。这里的问题是,你正试图将尚未入队的脚本解除队列。
,以消除家长添加脚本,提高儿童主题的wp_enqueue_scripts
行动的优先重视比父主题行动定义值。
// get_template_directory_uri(), if used in child theme, the parent theme directory URI will be returned,
// use get_stylesheet_directory_uri() to get the child's theme directory uri
add_action('wp_enqueue_scripts', 'child_theme_enqueue_scripts', 11);
function child_theme_enqueue_scripts()
{
wp_dequeue_script('parent-theme-script');
wp_enqueue_script('child-theme-script', get_stylesheet_directory_uri() . '/js/script.js');
}
要更换的脚本,例如,你想做出一些改变,并保留现有的依赖关系和定位有两种方式。
使用wp_enqueue_script
具有相同handle
名字,因为事实上,如果您尝试注册或排队已注册的手柄,新的参数会被忽略,有用的,如果剧本后来被父母本地化,以保持局部数据。
// default priority 10
add_action('wp_enqueue_scripts', 'child_theme_enqueue_scripts');
function child_theme_enqueue_scripts()
{
wp_enqueue_script('parent-theme-script', get_stylesheet_directory_uri() . '/js/script.js');
}
使用全局$wp_scripts
对象只修改所需的属性,例如,只改变src
已经排队或注册的脚本的属性。
// priority 11
add_action('wp_enqueue_scripts', 'child_theme_enqueue_scripts', 11);
function child_theme_enqueue_scripts()
{
global $wp_scripts;
$wp_scripts->registered[ 'parent-theme-script' ]->src = get_stylesheet_directory_uri() . '/js/script.js';
}
该子主题被加载第一,这个事实很实用,因为使用童工的主题并不是要取代,但更多的是除了主旋律。
感谢您提供其他信息。尽管使用PHP_INT_MAX似乎很漂亮OTT? –
可能是的,但我喜欢在儿童主题中使用它,以确保我的功能最后被锁定。这完全是你自己的偏好 –
让这个工作起作用的关键是确保你匹配你的父母主题中的'add_action'之后正在使用的内容。有时使用'wp_enqueue_scripts',有时使用'wp_footer',这取决于文件和主题。 – fidev