0

I'm setting up angular application inside a wordpress theme. Some Angular elements should check if a user is logged in and have a specific role to show some content. Wordpress is a PHP cms system and Angular is based on typescript. How to archive this.

What I am able to do is.

 console.log(document.body.classList.contains( 'logged-in' ));

But it seems very unsafe and its just the login status and has no user role check.

1 Answer 1

1

You can pass in PHP data to JavaScript using wp_localize_script:

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:

user_data.is_logged_in
user_data.user_roles

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.