admin管理员组

文章数量:1122832

  const { currentUser } = useSelect(
        ( select ) => ( {
            currentUser: select("core").getCurrentUser() 
        } ),
        []
    );

This gives me a user object, with the user id. But no role. How can I get the role?

Thank you

  const { currentUser } = useSelect(
        ( select ) => ( {
            currentUser: select("core").getCurrentUser() 
        } ),
        []
    );

This gives me a user object, with the user id. But no role. How can I get the role?

Thank you

Share Improve this question asked Sep 17, 2024 at 19:11 Justin WylllieJustin Wylllie 374 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

You can achieve this with the help of useSelect hook and select('core').getCurrentUser() here is the sample component for you.

import { useSelect } from '@wordpress/data';

const CurrentUserComponent = () => {
    const { currentUser } = useSelect((select) => ({
        currentUser: select('core').getCurrentUser(),
    }), []);

    // Here we are checking if currentUser is available or not.
    if (!currentUser) {
        return <p>Loading...</p>;
    }

    // Here we are accessing the roles.
    const roles = currentUser.roles || [];

    return (
        <div>
            <h2>Current User Roles:</h2>
            <ul>
                {roles.map(role => (
                    <li key={role}>{role}</li>
                ))}
            </ul>
        </div>
    );
};

export default CurrentUserComponent;

本文标签: wp adminCan I get the role of the currentUser in modern WordPress React