[英]php within js-file Wordpress
在.js文件中,我需要獲取Wordpress主題的模板目錄,即,我需要在js文件中獲取<?php bloginfo('template_directory');?>
的返回值。
這個想法是這樣的:
var blogTemplateDir = "<?php bloginfo('template_directory');?>";
如何做到這一點? 這樣做的標准方法(Wordpress)是什么?
Wordpress提供了wp_localize_script()
函數,當您在Wordpress中注冊PHP數組時,該函數可將PHP數組傳遞給.js文件。
它像這樣工作
1)使用wp_register_script()向Wordpress注冊腳本; 構建要發送到腳本的參數數組。
wp_enqueue_script('my-script','/path/to/script.js');
2)構建要發送到腳本的參數數組。
$params = array('foo' => 'bar','setting' => 123);
3)調用wp_localize_script()並給您的參數一個唯一的名稱。
wp_localize_script( 'my-script', 'MyScriptParams', $params );
4)您可以按以下方式訪問JavaScript中的變量:
<script>
alert(object_name.some_string);
</script>
注意:當您希望Wordpress在標頭中包含JavaScript文件時,需要使用wp_enqueue_script()。
一起拉
<?php
$myPlugin = new MyPlugin();
//Add some JS to the admin section
add_action('admin_enqueue_scripts', array($myPlugin, 'adminJavaScript'));
class MyPlugin{
public function adminJavaScript() {
$settings = array(
'foo' => 'bar',
'setting' => 123
);
wp_register_script('myJavaScriptName', plugins_url('/myJavaScript.min.js', __FILE__));
wp_localize_script('myJavaScriptName', 'settings', $settings); //pass any php settings to javascript
wp_enqueue_script('myJavaScriptName'); //load the JavaScript file
}
}
?>
<script>
alert(settings.foo);
</script>
如Erik先前所述,JavaScript文件的文件擴展名沒有意義,因為它最終都歸結為內容。 在開發過程中遇到這種情況時,我發現需要將以下內容添加到所謂的JavaScript文件的頂部:
<?php
//Let's set the header straight
header('Content-type: text/javascript');
//Get the WP-specifics, so that we can use constants and what not
$home_dir = preg_replace('^wp-content/plugins/[a-z0-9\-/]+^', '', getcwd());
include($home_dir . 'wp-load.php');
?>
這樣可以確保將定義放入JavaScript文件中,並且也可以將上面的示例與主題一起使用(只需確保將/plugins
更改為/themes
)即可。
javascript文件的文件擴展名沒有意義。 您可以像使用HTML頁面一樣使用PHP輸出JavaScript文件。 將JS文件包括為:
<script src="my_javascript_file.php"></script>
然后,您可以在JavaScript文件中使用問題的代碼行:
var blogTemplateDir = "<?php bloginfo('template_directory');?>";
將.js包裝在.php文件中,然后將其包含在您的上下文中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.