badcrocodile
3/19/2015 - 7:47 PM

Make WordPress php variables accessible to JS scripts with wp_localize_script

Make WordPress php variables accessible to JS scripts with wp_localize_script

<?php
// Referenced from http://ottopress.com/2010/passing-parameters-from-php-to-javascripts-in-plugins/
wp_enqueue_script('saos-event-calendar-scripts', plugins_url( 'js/scripts.js', __FILE__ ), array('jquery')); // scripts.js is my plugin's script that I need to access information such as site url
$params = array( // any parameter defined here will be accessible in the scripts.js file
	'site_url' => get_option('siteurl'),
	'plugin_dir' => plugins_url()
);
wp_localize_script('saos-event-calendar-scripts', 'saosEventCalendar', $params); // make the magic

// That's really all there is to it. I was expecting more :)

/* Usage (in your .js file):
var saosPluginDir = saosEventCalendar.plugin_dir + "/saos-event-calendar/";
var saosPathToAjax = saosEventCalendar.site_url + "/wp-admin/admin-ajax.php";
*/
?>