WordPress Options Passed To JavaScript #2

In our first article of this mini series, I explained how to pass with JSON from PHP to JS. Alternativly you can do this with the WordPress function wp_localize_script(), but contains some pitfalls. Therefore this little tutorial, also you should think about it in advance about these two solutions.

The functions serves to pass strings, at first to localize; so for the translate theme via Javascript. Therefore you can easily pass value and query them in Javascript. The most important point is, that this function can decode HTML Entities. Also important, that the script is recognized in advance; include it via wp_enqueue_script().

This example should explain it.

// on admin area enqueue the scripts
add_action( 'admin_enqueue_scripts', 'fb_admin_enqueue_scripts' );
function fb_admin_enqueue_scripts( $where ) {
	// separation in dev and live
	$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
	
	// enqueue of script, identifikation on the string-ID
	wp_enqueue_script(
		'example_script_id', 
		plugins_url( '/js/my-example-script' . $suffix. '.js', __FILE__ ), 	
		array( 'jquery' ),
		'',
		TRUE
	);
	
	// data via Array
	// array with data; also possible via get_option( 'my_option_string' )
	$data = array( 
		'some_string' => __( 'Some string to translate' ),
		'a_value' => '10'
	);
	// localize the data, identifier via script-ID and create object for JS
	wp_localize_script( 'example_script_id', 'js_object_name', $data );
}

With this little example everything is done on the PHP-side; the content of the array are known now as object js_object_name and can be use via the name-string js_object_name in JS.

Now some hints, which should help, if it comes to problems or which link to solutions via JSON directly.
The function wp_localize_script() decodes HTML Entities, which is kind of important, but not always the perfect solution. The function uses json_encode(), which can let to problems in multi-dimensional arrays in connection with the decoding of entities. As soon as the array has more than one dimension, I recommend JSON without the WP Core solution via wp_localize_script().

With WordPress 3.4 it will get better and the function will be more useful - let's see. I currently use on multiple dimensions rather JSON directly. The solution from the core would be nice, I like the handling and it would be clearly and comprehensively utilizable.

Comments are closed.

4 comments

  1. zane matthew

    I had actually stopped using wp_enqueue_scripts as I couldn't compile my js as needed.

  2. Brad Dalton

    Thanks for the code. Looks like 3.4 will be released this week

  3. mojtaba

    Thanks for the code

  4. Richard Guay

    Hi, you could always use AJAX calls as well. Have the JavaScript program query the server with a background AJAX call at page load. This also improved data security as it would not be printed in the page source.