Pass PHP Variables to Javascript in WordPress

An easy developer snippet for themes

In this example, I’m passing the Stylesheet Directory Uri (ref: wordpress) so the php function’s output is accessible in scripts.js. You can pass other variables to the vars object by adding more 'key' => 'value' pairs to the $variables_array.

functions.php file

$variables_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
wp_enqueue_script('my-theme-script', get_template_directory_uri() . 'script.js', '', '1.0' );
//after wp_enqueue_script
wp_localize_script( 'my-theme-script', 'vars', $variables_array );

script.js file

var templateUrl = vars.templateUrl;
//Use templateUrl in the js

Link Scripts and Css the right way in your WordPress Theme

Want to add your custom script or css to your theme? Just add this snippet into your functions.php file in the theme folder:

/**
 * enqueue scripts and styles from theme
 */
function my_custom_theme_scripts() {
	wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', null, '1.0');
	// Don't forget the styles!
	wp_enqueue_style('my-custom-css', get_template_directory_uri() . '/css/my-custom-css', null, '1.0');
}

add_action( 'wp_enqueue_scripts', 'my_custom_theme_scripts' );

Continue reading