Skip to content

Cadu de Castro Alves

How to check WordPress user role in an Angular application

WordPress, AngularJS1 min read

This was published originally on Stack Overflow.

You can pass in PHP data to JavaScript using wp_localize_script:

functions.php
1function so61079973_enqueue_scripts() {
2 // Register the script
3 wp_register_script( 'your-script', 'path/to/myscript.js' );
4
5 // Get the user object.
6 $user = get_userdata( $user_id );
7
8 // Get all the user roles as an array.
9 $user_roles = $user->roles;
10
11 // Localize the script with new data
12 $data_array = array(
13 'is_logged_in' => is_user_logged_in(),
14 'user_roles' => json_encode( $user_roles )
15 );
16
17 wp_localize_script( 'your-script', 'user_data', $data_array );
18
19 // 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);
© 2020 by Cadu de Castro Alves. All rights reserved.
Theme by LekoArts