Discovering a user's role in a WordPress site within an Angular application

I am currently in the process of integrating an Angular application into a WordPress theme. Certain Angular components need to verify if a user is logged in and has a specific role in order to display certain content. Since WordPress is built on PHP and Angular on TypeScript, I am seeking guidance on how to achieve this.

One option I have tried is:

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

However, this method appears to be insecure as it only checks the login status without verifying the user role.

Answer №1

Passing PHP data to JavaScript can be easily achieved using the wp_localize_script function in WordPress:

function custom_enqueue_scripts() {
    // Register a new script
    wp_register_script( 'my-script', 'path/to/myscript.js' );

    // Retrieve user information
    $user = get_userdata( $user_id );

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

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

    // Localize the script
    wp_localize_script( 'my-script', 'custom_data', $data_array );

    // Enqueue the script with localized data
    wp_enqueue_script( 'my-script' );
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

When working with JavaScript, retrieve the data by accessing the custom_data object:

custom_data.is_logged_in
custom_data.user_roles

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Double the names in a single <input>

Is it possible to assign two different names within a single input tag, like this: <input type='text' name='food' name='user_search_input'>? In my PHP file, I intend to use the input in two separate "if" clauses - one fo ...

Ways to Conceal/Deactivate Information in HTML

Welcome to my website mycareerpath.co.in. I am looking to remove the "FREE DOMAIN + 1GB HOSTING" from my site. Can anyone provide guidance on how to do this? Important Reminder Please remember to right click and inspect the page source for more informati ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Utilizing stream-based reading and writing to execute operations in MySQL database operations

I have extracted data from table tb_project_milestones and aim to insert this projectMilestoneRow into a table tb_xyz using streams. I referred to the documentation, but couldn't figure out how to execute it. Has anyone tried reading and inserting thr ...

Buefy: Secure the header of the table in place while allowing the rows to scroll freely

How can I make the header of the table component stay fixed while allowing only the rows to scroll? ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...

Encountering the error below while attempting to run ng serve

Having an issue with VSCode as a new user. When running ng serve, I encountered the following error message: PS C:\Windows\System32\x-app> ng serve --configuration=it An unhandled exception occurred: Workspace config file cannot le loa ...

The Angular 4 iframe fails to show the content from the src link webpage

Template: <iframe width="100%" height="100%" [src]="url"></iframe> Component : I have successfully converted the URL into a safeUrl: ngOnInit() { this.url = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.google.com/ ...

Exploring the functionality of uiRouter using the requirejs framework

I've been struggling with a problem for a while now and haven't found any solutions in other posts related to testing uiRouter with requirejs. I have a basic controller set up that uses $state.go to switch states when a button is clicked. runsCo ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : https://i.sstatic.net/myJAf.png On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Ri ...

Enable the click functionality for a disabled MI TextField

I'm utilizing a disabled TextField in my project and updating it using React Hooks useState to modify the value property of the TextField. const [employee , setEmployee] = React.useState('') <TextField fullWidth ...

Extracting IDs from an array response in Vue.js

Hey there, I have a scenario where I am fetching response data using Vue.js with Axios from Laravel: Here is my example method in Vue.js: getApps(page = 1){ axios.get('/api/getappforms') .then(response => { apps = res ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

The latest value has replaced the state's previous value

In my current function, I am updating an array stored in state based on the status of 9 tables. Each table calls this function to check its status, and if true, it is added to the array. const [projectSpaceTypeWarning, setProjectSpaceTypeWarning] = useSta ...

Trouble with storing data in Angular Reactive Form

During my work on a project involving reactive forms, I encountered an issue with form submission. I had implemented a 'Submit' button that should submit the form upon clicking. Additionally, there was an anchor tag that, when clicked, added new ...

Collapsed ReactJS: Techniques for compressing the Material UI TreeView following expansion

My issue involves a Material UI treeView. After expanding it, an API call is made, but the node in the treeView remains open. I have attempted to use onNodeToggle without success. Below is my code: <TreeView className={classes.root1} defaultExpandI ...

Creating interactive touch events on an HTML canvas with a scrollbar

Hello there, I'm currently working on developing a touch-enabled signing app that utilizes 2 HTML Canvases. The issue I am encountering is that when I scroll to focus on the second canvas, my ability to sign on it stops working properly. It appears t ...

The required property 'intersect' is not found in the type 'import("cesium").BoundingSphere'

Incorporating Cesium into a ReactJs application has been my recent project. I have successfully displayed various factories in the cesium viewer and drawn polygon grids on their coordinates. However, I am encountering confusion with one particular aspect. ...

How can you navigate to a particular page within a Single Page Application using NodeNS?

My NodeJS server is hosting a single page application that was built using Angular5. In certain circumstances, I need to direct users to a specific page within the application. For instance, during a designated time period, I want users to be redirected t ...

Submit Form using Ajax - Update text in HTML element upon click

As I am working on developing a message system, I encountered an issue where the message content is not opening correctly in my template when clicking the "See" button. My intention is to implement an Ajax call that will replace the content with jQuery .te ...