問題描述
為了提高效率,我們試圖將某些 JS 指令碼僅繫結在一個主題的特定頁面模板上,該主題是一個表單:page-with-form.php
在主題 functions.php 中,我們定義了一個 init_method:
function my_init_method(){
$dir = get_bloginfo('stylesheet_directory')."/js/jquery.js";
wp_deregister_script('jquery');
wp_register_script('jquery',$dir);
wp_enqueue_script('jquery');
$dir = get_bloginfo('stylesheet_directory')."/js/jquery.validate.min.js";
wp_deregister_script('jquery.validate.min');
wp_register_script('jquery.validate',$dir);
wp_enqueue_script('jquery.validate.min');
$dir = get_bloginfo('stylesheet_directory')."/js/funcion.js";
wp_deregister_script('funcion');
wp_register_script('funcion',$dir);
wp_enqueue_script('funcion');
}
然後我們預計我們可以在 page-with-form.php 頁面模板 (before get_header()) 的貼片線上新增:
add_action('init', 'my_init_method');
-
這不可能嗎
-
我們是否強制將一個 if 規則新增到 functions.php 函式來檢測我們在該頁面上?
基於答案的程式碼修改:在頁面模板上直接載入函式,不需要 add_action(“init” …
my_init_method();
...
get_header();
最佳解決方案
init 比頁面模板載入早很多,而不是排隊的合適位置 (儘管許多教程和檔案都使用它) 。
將您的功能掛接到 wp_enqueue_scripts,並確保您在 wp_head()呼叫模板之前進行掛接。
次佳解決方案
除了使用正確的鉤子 (由 @Rarst 指出) 之外,您需要將功能程式碼移至 functions.php,並將功能內容包裝在 if ( is_page( 'page-with-form' ) )條件中。
第三種解決方案
當您載入模板檔案時,您已經透過了'template_redirect'鉤子,太晚了 (參見:Plugin/Action API Reference) 。
您需要在您的 functions.php 檔案中設定 add_action 呼叫,該檔案在 after_setup_theme 鉤子之前載入 – 這是主題的第一個可用鉤子。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。