Easy question: I’m trying to understand wp_localize_script
.
Does wp_localize_script
call a JavaScript function or does it simply pass PHP parameters to JavaScript?
I want to pass PHP parameters to a JavaScript function and call the JS function.
1 Answer
wp_localize_script
takes an array of data (in PHP) spits out a javascript. It’s a way for you to add dynamic data for a specific script to the front end without having to hook into wp_head or wp_footer and echo it out yourself. More over, wp_localize_script
outputs your data right above the script you enqueued. Hooking into wp_head
or wp_footer
won’t do that.
wp_localize_script
does not call javascript functions. It’s a way to do exactly what you want: pass dynamic data from the server side (PHP) to the client side (javascript).
An Example
Your theme needs to take a piece of post meta data and make it accessible to a javascript function.
So you’d hook into wp_enqueue_scripts
and do the following…
<?php
add_action( 'wp_enqueue_scripts', 'wpse34008_enqueue' );
function wpse34008_enqueue()
{
// if we're not on a singular page, bail
if( ! is_singular() ) return;
global $post;
if( empty( $post ) ) $post = get_queried_object();
// enqueue your script...
wp_enqueue_script( 'wpse34008-script', 'http://example.com/path/to/script.js' );
wp_localize_script(
'wpse34008-script',
'wpse34008',
array(
'meta' => get_post_meta( $post->ID, '_wpse34008_meta', true )
)
);
}
Then somewhere the enqueued script.js
file, you can get the post meta like this…
// somewhere in the js file
someFunction( wpse34008.meta );
Make sense?