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 1


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...

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' );

            '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?

  • 1
    Great explanation! I understand it now. Thanks so much.
    – Laxmidi
    Nov 17, 2011 at 19:24
  • Well explained. +1
    – kaiser
    Nov 17, 2011 at 22:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.