Site Settings Object for Your Front-End Scripts
Prints a small window.siteSettings object with the home URL, REST API root, AJAX URL, language and, for logged-in users, a REST nonce, so your custom JavaScript never hard-codes addresses.
Opens WPIDE on
Code
add_action( 'wp_enqueue_scripts', function () {
$data = array(
'homeUrl' => home_url( '/' ),
'restUrl' => esc_url_raw( rest_url() ),
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'locale' => determine_locale(),
'loggedIn' => is_user_logged_in(),
);
// The nonce authenticates REST requests from logged-in users only.
if ( is_user_logged_in() ) {
$data['restNonce'] = wp_create_nonce( 'wp_rest' );
}
wp_register_script( 'wpide-site-settings', false, array(), '1.0', false );
wp_enqueue_script( 'wpide-site-settings' );
wp_add_inline_script( 'wpide-site-settings', 'window.siteSettings = ' . wp_json_encode( $data ) . ';', 'before' );
} );
Notes
Read it in your scripts as window.siteSettings.restUrl; add your own values to the $data array.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.