Skip to content

Instantly share code, notes, and snippets.

@franhaselden
Created November 24, 2015 12:44
Show Gist options
  • Save franhaselden/a85c97148ef3d99efa15 to your computer and use it in GitHub Desktop.
Save franhaselden/a85c97148ef3d99efa15 to your computer and use it in GitHub Desktop.
Localize scripts - Wordpress function to enqueue scripts along with data passed from serverside (great way to access Wordpress functions like *stylesheet_directory_uri in scripts
wp_register_script( 'home', get_template_directory_uri().'/js/home.js', array( 'site' ) ); // resgister the script and what you want it to load after
$home_data = array(
'theme_url' => get_stylesheet_directory_uri() // create an array with any data you want to pass
);
wp_localize_script( 'home', 'home_data', $home_data ); // localise that data and pass it through
wp_enqueue_script( 'home' ); // enqueue the script ready for loading
var themeURL = home_data.theme_url; // now you can access data from the array in your JS
console.log(themeURL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment