I’m trying to pass a variable to a javascript file from a plugin. Here is my plugin code:
<?php
/**
* @package JS Test
* @version 1.0
*/
/*
Plugin Name: JS Test
Description: JS Test.
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_enqueue_script('my-java-script');
wp_localize_script('my-java-script', 'php_params', $params);
}
Here is the jstest.js file:
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
What I get is this error in JavaScript:
ReferenceError: php_params is not defined
Anybody see what I’m doing wrong?
You Don’t need to enqueue a script just for your localized parameters you can use your testjs for that, here is a quick plugin i cooked up to test:
as you can see here the
wp_localized_script
uses the same script as you enqueue and not a fake script.