wp_enqueue_script したjsファイルにphpから変数を渡す

タイトルどおりの事がしたく、調べてみるととても簡単だったのでメモ。

wp_localize_scriptというタグを使います。

たとえばphpから下のようにjsを読ませて、

wp_register_script( 'sample', get_path . '/js/sample.js', "",true);
wp_enqueue_script( 'sample' );

wp_localize_scriptを追加します。こんな形になります。

wp_register_script( 'sample', get_path . '/js/sample.js', "",true);
wp_enqueue_script( 'sample' );
$variable_array = array( 'hoge' => 'huga');
wp_localize_script( 'sample', 'variable_array ', $variable_array );            

すると、sample.js側ではvariable_array オブジェクト無いのhoge を取ることができます。

console.log(variable_array.hoge);

ワードプレスのテーマ内のJSでajaxする時などによく使っています。


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>