Last active
May 7, 2020 12:02
-
-
Save vanaf1979/a749804feb050dec72f47a1d6fd2dff8 to your computer and use it in GitHub Desktop.
Setup Axios for the WordPress Rest Api https://since1979.dev/snippet-014-setup-axios-for-the-wordpress-rest-api/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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