在典型的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