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" />';
- The first argument of
wp_localize_script()must equal the first argument of
wp_enqueue_script()— specifically matching the handles
- The second argument of
wp_localize_script()is the object that you will access data from in your JS
- The third argument of
wp_localize_script()is an array of data you want to pass