Skip to main content

How To Pass PHP Data To JavaScript In WordPress

By July 25, 2017Blog, Wordpress
WordPress Tutorials by Allure Web Solutions

This is a super valuable method of passing data to our JavaScript from PHP within WordPress. Prior to this, I was using PHP to create data attributes to pass data. Then I would use JS to read those data attributes. With this method, you can skip the inefficiencies created by passing data through attributes and access the PHP data directly. In the example below, I show how to pass the current path of the plugin I’m working on in order to use it in calling a loading gif from my JavaScript.

The PHP

Add this to your functions.php or wherever your are enqueuing your custom JS script.

wp_enqueue_script('script', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), '1.0', false);
wp_localize_script('script, 'fromPHP', array(
    'pluginUrl' => plugin_dir_url(__FILE__),
    'ajax_url' => admin_url('admin-ajax.php')
));

Usage in JS

With this JS, we are able to access the path to the loading gif.

var loader = '<img class="loading" src="' + fromPHP.pluginUrl + '/images/loading.gif" />';

Notes

  1. The first argument of wp_localize_script() must equal the first argument of wp_enqueue_script()  — specifically matching the handles
  2. The second argument of wp_localize_script() is the object that you will access data from in your JS
  3. The third argument of wp_localize_script() is an array of data you want to pass
allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017