— WordPress, AngularJS — 1 min read
This was published originally on Stack Overflow.
You can pass in PHP data to JavaScript using wp_localize_script:
1function so61079973_enqueue_scripts() {2 // Register the script3 wp_register_script( 'your-script', 'path/to/myscript.js' );45 // Get the user object.6 $user = get_userdata( $user_id );78 // Get all the user roles as an array.9 $user_roles = $user->roles;1011 // Localize the script with new data12 $data_array = array(13 'is_logged_in' => is_user_logged_in(),14 'user_roles' => json_encode( $user_roles )15 );1617 wp_localize_script( 'your-script', 'user_data', $data_array );1819 // Enqueued script with localized data.20 wp_enqueue_script( 'your-script' );21}22add_action('wp_enqueue_scripts', 'so61079973_enqueue_scripts');
Then, in the JavaScript, you can get the data by calling the user_data
object:
1console.log(user_data.is_logged_in);2console.log(user_data.user_roles);