問題描述
我正在父主題中加載一些 JavaScript 文件。父主題中的路徑是:
scripts > custom.js
在子主題中,我創建了相同的路徑 (scripts > custom.js),並更改了 custom.js 文件中的一些 jQuery 。
問題是這些更改沒有被應用。這是在孩子主題中更改這些文件的錯誤方法嗎?
最佳解決方案
兒童主題只會覆蓋包含在 get_template_part 或 get_header 等函數中的 php 文件 (如 header.php) 。
將腳本添加到 WordPress 的正確方法是使用 wp_enqueue_script 。如果您的父主題使用此方法,您可以使用 wp_dequeue_script 並排隊自己來覆蓋 JS 文件。
像這樣…
<?php
// hook in late to make sure the parent theme's registration
// has fired so you can undo it. Otherwise the parent will simply
// enqueue its script anyway.
add_action('wp_enqueue_scripts', 'wpse26822_script_fix', 100);
function wpse26822_script_fix()
{
wp_dequeue_script('parent_theme_script_handle');
wp_enqueue_script('child_theme_script_handle', get_stylesheet_directory_uri().'/scripts/yourjs.js', array('jquery'));
}
如果父主題沒有使用 wp_enqueue_script,那麼它可能是掛在 wp_head(或 wp_footer) 中來回顯出那裏的腳本。所以你可以使用 remove_action 來擺脱那些回應腳本的函數,然後排列你自己的腳本。
如果腳本被硬編碼到模板文件中,那麼您只需要在沒有腳本標籤的子主題中替換該模板文件。
如果他們使用了使用 get_stylesheet_directory_uri 的 wp_enqueue_script 調用,那麼你不應該做任何事情。既然沒有發生這種情況,那麼你只需要戳一下,看看主題作者做了什麼。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。