Photo of two young men crouching and smiling

Check WordPress user roles in PHP

It’s pretty common to want to check user roles when doing WordPress stuff, so here’s a function for it!

It’s a pretty simple function, accepting two arguments:

  1. A user role to check for
  2. A user ID to check against

First we check if a valid user ID number is provided, and if so, we call get_userdata on the ID.

If no user ID is passed to the function, we call wp_get_current_user, which will return 0 for non-logged-in users.

Then we just check if the user role to check for passed to the function is present in the array of the user’s roles.

<?php
function check_user_role($role, $user_id = null)
{
    if (is_numeric($user_id))
        $user = get_userdata($user_id);
    else
        $user = wp_get_current_user();
    if (empty($user))
        return false;
    return in_array($role, (array) $user->roles);
}

An example

Here’s an example where we check if the currently logged in user is an editor, and if so, we’ll add some CSS to hide the comments option in the admin sidebar.

<?php
if (check_user_role('editor')) {
    function hide_unused_menu_items()
    {
        ?>
        <style>
            #menu-comments {
                display: none;
            }
        </style>
        <?php
    }
    add_action('admin_footer', 'hide_unused_menu_items');
}

You can use it on the frontend too, but I’ve most frequently found myself using it to customise experiences in the backend for specific user roles.

Recent posts