WordPress How To Pass PHP Values To JavaScript In Plugins

Share

While creating a plugin if you want to pass some values generated by PHP to a JavaScript file, the WordPress way, follow the below steps. It’s really very easy –

1. Put the values in an array For example –

 
$params = array('pluginpath' => plugins_url(),'abc' => $xyz); 

2. Register the JavaScript file. For example –

 
wp_register_script('jsfile', plugins_url('/', __FILE__) . 'js/jsfile.js');

3. Make the PHP data available to the registered script. For example –

 
wp_localize_script( 'jsfile', 'phpvalues', $params );

4. Link the script file. For example –

 
wp_enqueue_script('jsfile');

5. Use the values in JavaScript file as below –

alert(phpvalues.pluginpath);
alert(phpvalues.abc);

Full example code in PHP

 
function example_admin_init() {
     $params = array('pluginpath' => plugins_url(),'abc' => $xyz); 
     wp_register_script('jsfile', plugins_url('/', __FILE__) . 'js/jsfile.js');
     wp_localize_script( 'jsfile', 'phpvalues', $params );
     wp_enqueue_script('jsfile');
}
add_action('wp_enqueue_scripts', 'example_admin_init');

Hope it was clear. Happy coding 🙂

This entry was posted in Wordpress and tagged , , , . Bookmark the permalink.
 

Leave a Reply

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

*