問題描述
我需要在 javascript 檔案中包含我的主題檔案的路徑。我該怎麼辦?我已經嘗試過:
var templateUrl = "<?php get_stylesheet_directory_uri(); ?>";
function LightboxOptions() {
this.fileLoadingImage = "'"+templateUrl+"/img/loading.gif'";
this.fileCloseImage = "'"+templateUrl+"/img/close.png'";
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
這不給我的路徑,只是插入<?php get_stylesheet_directory_uri(); ?>
而不是實際的路徑。有任何想法嗎?提前致謝!
最佳解決方案
你要找的是 wp_localize_script function 。
當使用指令碼時,您可以使用它
wp_register_script( 'my-script', 'myscript_url' );
wp_enqueue_script( 'my-script' );
$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
//after wp_enqueue_script
wp_localize_script( 'my-script', 'object_name', $translation_array );
在你的 style.js 中,會有:
var templateUrl = object_name.templateUrl;
...
次佳解決方案
以下是在 javascript 檔案中新增主題路徑的兩種方法。
1) 您可以使用您的 functions.php 檔案中由 wordpress 建議的 wp_localize_script()。這將在標題中建立一個 JavaScript 物件,這將在執行時可用於您的指令碼。
示例:
wp_register_script('custom-js',get_stylesheet_directory_uri().'/js/custom.js',array(),NULL,true);
wp_enqueue_script('custom-js');
$wnm_custom = array( 'stylesheet_directory_uri' => get_stylesheet_directory_uri() );
wp_localize_script( 'custom-js', 'directory_uri', $wnm_custom );
並可以在您的 js 檔案中使用如下:
alert(directory_uri.stylesheet_directory_uri);
2) 您可以建立一個將模板目錄 uri 儲存在變數中的 JavaScript 程式碼片段,並在以後使用如下:將此程式碼新增到 header.php 檔案中,然後再使用此路徑。例:
<script type="text/javascript">
var stylesheet_directory_uri = "<?php get_stylesheet_directory_uri(); ?>";
</script>
並可以在您的 js 檔案中使用如下:
alert(stylesheet_directory_uri);
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。