Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

up vote 5 down vote accepted

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?

share|improve this answer
1  
Great explanation! I understand it now. Thanks so much. –  Laxmidi Nov 17 '11 at 19:24
    
Well explained. +1 –  kaiser Nov 17 '11 at 22:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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