How to check WordPress user role in an Angular application

04/07/2020

This was published originally on Stack Overflow.

You can pass in PHP data to JavaScript using wp_localize_script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

function so61079973_enqueue_scripts() {
    // Register the script
    wp_register_script( 'your-script', 'path/to/myscript.js' );

    // Get the user object.
    $user = get_userdata( $user_id );

    // Get all the user roles as an array.
    $user_roles = $user->roles;

    // Localize the script with new data
    $data_array = array(
        'is_logged_in' => is_user_logged_in(),
        'user_roles' => json_encode( $user_roles )
    );

    wp_localize_script( 'your-script', 'user_data', $data_array );

    // Enqueued script with localized data.
    wp_enqueue_script( 'your-script' );
}
add_action('wp_enqueue_scripts', 'so61079973_enqueue_scripts');

?>

Then, in the JavaScript, you can get the data by calling the user_data object:

1
2
console.log(user_data.is_logged_in);
console.log(user_data.user_roles);