問題描述
我想知道最有效的方法是新增一個特定於 post 和/或 page 的 javascript 檔案。
以下是我想出的幾個解決方案:
-
切換到 HTML 編輯檢視,並在其中釋出您的 JavaScript(非常糟糕的解決方案)
-
關鍵字& 價值對
-
在 footer.php 中,根據您所在的頁面載入 JavaScript 檔案 (這會導致很多條件)
在旁邊的說明中,沒有一個 JavaScript 檔案將在頁面之間共享 – 它將確切地與您當前正在檢視的內容相關。
有什麼想法嗎?
最佳解決方案
我認為效率和使用適當的 wordpress 方法新增 javascript 之間的最佳平衡將是沿著這些行新增一些東西到你的主題 functions.php 檔案。例如:
的 functions.php:
function load_scripts() {
global $post;
if( is_page() || is_single() )
{
switch($post->post_name) // post_name is the post slug which is more consistent for matching to here
{
case 'home':
wp_enqueue_script('home', get_template_directory_uri() . '/js/home.js', array('jquery'), '', false);
break;
case 'about-page':
wp_enqueue_script('about', get_template_directory_uri() . '/js/about-page.js', array('jquery'), '', true);
break;
case 'some-post':
wp_enqueue_script('somepost', get_template_directory_uri() . '/js/somepost.js', array('jquery'), '1.6', true);
break;
}
}
}
add_action('wp_enqueue_scripts', 'load_scripts');
這可以讓您完全控制什麼被載入到哪裡,您的主題中的一個集中位置的 functions.php 檔案用於編輯什麼被載入到哪裡:和這種方式使用 wordpress 方法來安全地新增 JavaScript 到您的帖子和頁面。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。