Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress - Pass PHP values into JS
<?php
add_action( 'wp_enqueue_scripts', function() {
$version = SCRIPT_DEBUG ? time() : null;
wp_enqueue_script(
'_my_js_app',
get_template_directory_uri() . '/_my_js_app.js',
[],
$version,
true // in footer.
);
/**
* Pass our variables into our JS.
* @see https://codex.wordpress.org/Function_Reference/wp_localize_script
*/
wp_localize_script(
'_my_js_app',
'my_theme_data',
[
'nonce' => wp_create_nonce( 'wp_rest' ),
'path' => $path,
'blogname' => get_option( 'blogname' ),
'blogdescription' => get_option( 'blogdescription' ),
'posts_per_page' => get_option( 'posts_per_page' ),
'URL' => array(
'api' => esc_url_raw( get_rest_url( null, '/wp/v2' ) ),
'root' => esc_url_raw( $url ),
),
'user_id' => get_current_user_id(),
'user_email' => wp_get_current_user()->user_email,
'any_other_php_var' => 'value from php for js here',
]
);
} );
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.