Script Localization with JQuery in WordPress

Today, most plugin developers use JQuery to perform client-side tasks.  This adds a lot of functionality to your WordPress plugin, but what if you want to pass server-side data to these client-side files?

After your JQuery files have been included to a page, then you can use the wp_localize_script() function to pass your server-side data to these files.  All data is passed as a string, but you can convert it to a number if needed.  If you don’t know how to include files to a WordPress page, then check out this post, Include Javascript and CSS files through your WordPress Plugin.

<?php
     wp_enqueue_script( 'some_handle' );
     $passed_data = array( ’name' =>  ‘Kyle Benk' , ‘job_status' => ‘Wordpress Developer' );
     wp_localize_script( 'some_handle', ‘passed_data', $passed_data );
?>

You can then use this data in your JQuery script file like so:

$(document).ready(function(){
     console.log(“Name: “ + passed_data.name + “ Job Status: “ + passed_data.job_status);
});

How else can you use script localization with JQuery to your advantage? Here is an example of passing a translated string:

<?php
     wp_enqueue_script( 'some_handle' );
     $passed_data = array( ’string' => __( 'Some string to translate' ));
     wp_localize_script( 'some_handle', ’passed_data', $passed_data );
?>
$(document).ready(function(){
     console.log(“Translated String: “ + passed_data.string);
});

If your console outputs an undefined variable error for your passed data, then it means your wp_localize_script() function did not send the data properly. Most commonly this is because you are calling the wp_localize_script() function before the script has been included. So, make sure you enqueue the script before trying to localize it. To check for this error use this JQuery code:

if (typeof(passed_data) != "undefined" && passed_data !== null) {
     console.log(“Variable is set");
} else {
     console.log(“Undefined or null variable");
}

Leave a Reply

Your email address will not be published. Required fields are marked *