Using PHP variables in JavaScript with wp_localize_script

There is many ways to pass dynamic variables to JavaScript. An easy way would be just to define the JavaScript variables in the <head> echoing the PHP variables.

This will of course work, but there is a WordPress-way to do it as well.

The function wp_localize_script gives you the ability to write a JavaScript object with multiple variables defined. The function must be called after your script has been enqueued. Simply pass in the name of your script handle, the object name and your data.

function mytheme_wp_enqueue_scripts() {
wp_enqueue_script( 'mytheme_script', get_template_directory_uri() . '/js/main.js', array('jquery'), false, true );
wp_localize_script( 'mytheme_script', 'myObj', array(
'homeUrl' => home_url(),
'translatableString' => __( 'A String' )
) );
}
add_action( 'wp_enqueue_scripts', 'mytheme_wp_enqueue_scripts' );

This will print the following code before your script is included

<script type='text/javascript'>
/* <!--[<span class="hiddenSpellError" pre=""-->CDATA[ */
var myObj = {"homeUrl":"http:\/\/forsakringskassan.dev","translatableString":"A String"};
/* ]]> */
</script>

Then you are free to use the variable in your JavaScript in which ever way you want!

alert(myObj.translatableString)

That’s all — Happy coding!

Advertisements
About

Web Developer @ Oakwood Creative - www.oakwood.se

Tagged with: , , , ,
Posted in Intermediate
3 comments on “Using PHP variables in JavaScript with wp_localize_script
  1. […] Using PHP variables in JavaScript with wp_localize_script « WordPress Quick Tips […]

  2. it’s broken on wp 3.4.1

  3. “An easy way would be just to define the JavaScript variables in the echoing the PHP variables.” WOW that’s all I needed… I’ve spend like 5 hours trying to get the worthless localize script working in WordPress… Even following WordPress’s own tutorial and not changing anything it didn’t work. I have no idea why it needs to be so complicated…

    But thank you for that tip at the beginning! It’s the only thing I’ve been able to get to work in the least, thank you so much!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About

WordPress Quick Tips is a blog supplying great tips about WordPress.

We hope to create a great knowledge resource for WordPress developers as well as serving a reminder for all the forgetful ones.

The blog is created and run by Vincent of Oakwood Creative

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 120 other followers

%d bloggers like this: