Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active March 6, 2019 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/8821bc8a8adee3abc71cf4d0dee896f0 to your computer and use it in GitHub Desktop.
Save davidsword/8821bc8a8adee3abc71cf4d0dee896f0 to your computer and use it in GitHub Desktop.
WordPress - Pass PHP values into JS
<?php
wp_scripts()->add_data(
'my_js_theme',
'my_theme_data',
sprintf(
'var my_theme_data = %s;',
wp_json_encode( [
'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