LoginSignup
7

More than 5 years have passed since last update.

wp_localize_script() テーマファイルのURLなどをjsファイルに渡す

Posted at

wp_localize_script()はWordPressの関数です。
動的に取得したテーマファイルのURLなどをjsファイルに渡すことができます。

head要素に以下を記述します。

php
wp_enqueue_script('global', get_template_directory_uri().'/js/global.js',array('jquery'));
wp_localize_script('global', 'images_path', array('url' => get_template_directory_uri().'/images/'));

htmlにオブジェクト形式で出力されます。

javascript
/* <![CDATA[ */
var images_path = {"url":"http://***\/wp\/wp-content\/themes\/mytheme\/images\/"};
/* ]]> */

jsファイルでオブジェクトの値を取得します。

JavaScrpit
var img_path = images_path.url; //テーマファイルのimagesディリクトリを取得

書式

php
wp_localize_script(
    'global', //値を渡すjsファイルのハンドル名
    'images_path', //任意のオブジェクト名
    array('url' => get_template_directory_uri().'/images/') //プロバティ
);

wp_enqueue_script()で値を渡すjsファイルのハンドル名を設定して、wp_localize_script()から値を渡す、という流れが良さそうです。

参考:
[Javascriptでサイトのデータを扱う方法]http://morilog.com/wordpress/js/wp_localize_script/
[動的なオプション値を、外部 javascript に適用する]http://tenman.info/labo/snip/archives/5489

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7