問題描述

我正在父主題中載入一些 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。