Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* namespace_enqueue_scripts.
*
* Enqueue a javascripty file called scripts.js and
* Add a localization object called mynamespace with,
* The base rest api url and a security nonce
*
* @see https://since1979.dev/snippet-014-setup-axios-for-the-wordpress-rest-api/
*
* @uses wp_enqueue_script() https://developer.wordpress.org/reference/functions/wp_enqueue_script/
* @uses get_template_directory_uri() https://developer.wordpress.org/reference/functions/get_template_directory_uri/
* @uses wp_localize_script() https://developer.wordpress.org/reference/functions/wp_localize_script/
* @uses rest_url() https://developer.wordpress.org/reference/functions/rest_url/
* @uses esc_url_raw() https://developer.wordpress.org/reference/functions/esc_url_raw/
* @uses wp_create_nonce() https://developer.wordpress.org/reference/functions/wp_create_nonce/
*/
function namespace_enqueue_scripts()
{
wp_enqueue_script('namespace-scripts', get_template_directory_uri() . '/scripts.js', array(), '1.0.0', true);
wp_localize_script('namespace-scripts', 'mynamespace', array(
'rootapiurl' => esc_url_raw(rest_url()),
'nonce' => wp_create_nonce('wp_rest')
));
}
/**
* Hook: wp_enqueue_scripts.
*
* @uses add_action() https://developer.wordpress.org/reference/functions/add_action/
* @uses wp_enqueue_scripts https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
*/
add_action('wp_enqueue_scripts', 'namespace_enqueue_scripts', 100, 0);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.