Last active
March 6, 2019 15:59
-
-
Save davidsword/5923a55bcb59d404821cde10fc15b566 to your computer and use it in GitHub Desktop.
WordPress - Pass PHP values into JS
This file contains hidden or 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 | |
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