Skip to content

Instantly share code, notes, and snippets.

@michelmany
Last active November 30, 2016 14:58
Show Gist options
  • Save michelmany/73fbaeb7236ca954ac8ec1c51a62341a to your computer and use it in GitHub Desktop.
Save michelmany/73fbaeb7236ca954ac8ec1c51a62341a to your computer and use it in GitHub Desktop.
Localizes a registered script with data for a JavaScript variable. https://codex.wordpress.org/Function_Reference/wp_localize_script
// Register the script
wp_register_script( 'custom-scripts', get_stylesheet_directory_uri() . '/js/custom-scripts.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10'
);
wp_localize_script( 'custom-scripts', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'custom-scripts' );
// alerts 'Some string to translate'
alert( object_name.some_string);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment