Passing WordPress configuration settings to your Javascript files

I always pass data to Javascript from PHP but I’ve never thought about passing local wp-config defines but there is no reason why you can’t!

May come back to this to add more information but for now its a quick n dirty documentation of what I’ve just setup in a local environment.

In my wp-config.php I’ve setup a define for a local url that I can use through-out my dev files.

/**
 * custom define to local environment
 */
define('LOCAL_URL', 'https://mylocalurl.test');

Now I can setup the define at the top of my small PHP plugin to check if I’m in my local or production site.

if ( ! defined( 'LOCAL_URL' ) ) {
	define( 'LOCAL_URL', 'https://myproductionurl.com' );
}

So now I can pass the define to my scripts using the function wp_localize_script();

/**
 * Loads all script and style dependencies
 *
 * @return void
 */
function my_custom_enqueue_script_loading() {
    wp_enqueue_script('myhandle',plugins_url('js/custom.js',__FILE__));
    wp_localize_script('myhandle', 'settings', array('url' => LOCAL_URL));
}
add_action( 'wp_enqueue_scripts', 'my_custom_enqueue_script_loading' );

So now I can share the setting that’s been set once in my plugin with my Javascript file by setting a constant like so…

var localUrl = settings.url;

Very skeleton post at the moment but hopefully it gets the concept across. I’m interested to see what feedback I get and how this post develops.

Leave a comment

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