How to Pass PHP Data and Strings to JavaScript in WordPress

It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code.

If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you.

This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.

Why the need to Pass Data to JavaScript

Let me illustrate some typical scenarios for the need to pass data to JavaScript. For instance, sometimes we need to get these values into your JavaScript code:

  • Homepage, admin, plugin, theme, or ajax URLs,
  • Translatable strings, or
  • A theme or WordPress option.

The Common Way of Passing Data

Let's say we have a jQuery file called myLibrary.js which we will include in our WordPress site:

We enqueue it in our functions.php with the following code:

Now the question is how can we populate the home and pleaseWaitLabel properties? You might have instinctively added something like this in your header.php to get the data you need:

This works as intended; however, WordPress has provided us with a better and shorter way to do this.

The WordPress Way

The recommended way of passing data to JavaScript is by using the wp_localize_script function. This function is meant to be used after you enqueue a script using wp_enqueue_scripts.

Here're the parameters:

  • $handle. The handle to the enqueued script to bind the values to
  • $objectName. The JavaScript object that will hold all the values of $arrayOfValues
  • $arrayOfValues. An associative array containing the name and values to be passed to the script

After calling this function, the $objectName variable will become available within the specified script.

Implementing wp_localize_script

Let's adjust the earlier example to use our new method of passing data. First, we enqueue the script then call wp_localize_script in our functions.php:

Now our home and pleaseWaitLabel values can now be accessed inside our jQuery library via the php_vars variable.

Since we used wp_localize_script, we won't have to run anything in our header.php and we can safely remove the contents of the <script> tag:

We can also remove the additional properties from our jQuery script. It can now be simplified to this:

Conclusion

By using wp_localize_script, our code is simpler and our header.php is cleaner. Hopefully, you can use this function in your own code and enjoy its benefits.

I hope you enjoyed this article. I highly appreciate any feedback, comments and suggestions.

Will you be using this in one of your projects? Share your thoughts below!

Tags:

Comments

Related Articles