問題描述

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