問題描述
為了提高效率,我們試圖將某些 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。