How to retrieve WordPress user permissions using user ID

I’m working on a system where I need to verify what permissions a specific user has in WordPress, but I only have their user ID to work with. The problem is that the user I want to check isn’t currently logged in. I know about functions like user_can() but I’m not sure how to apply them when checking someone else’s capabilities rather than the current logged-in user. My situation involves an admin panel where staff members process orders on behalf of customers, so I need to validate the customer’s role programmatically. What’s the best approach to fetch user role information when you have the user ID but they’re not the active session user?

You can also use the WP_User class constructor directly. Just do $user = new WP_User($user_id) and you’ll get all the same capability checking methods. This works great when you’re doing multiple permission checks for the same user - you only create the object once. I use this all the time for custom admin interfaces where staff need to do things on behalf of customers. The user object loads all role and capability data whether they’re logged in or not, so it’s perfect for admin panels.

you can also just use user_can($user_id, 'capability') with the user ID direct - no need to grab the whole user object first. perfect for quick perm check without the extra overhead. just double-check the user ID exists or you’ll get false back.

To check the permissions of a WordPress user based on their ID without them being logged in, you can utilize the get_user_by() function to retrieve the user object. Here’s a straightforward method:

$user = get_user_by('ID', $user_id);
if ($user) {
    if ($user->has_cap('manage_options')) {
        // User has admin capabilities
    }
    // Check for specific roles
    if (in_array('customer', $user->roles)) {
        // User is a customer
    }
}

By using has_cap(), you can effectively verify the user’s capabilities outside of the current session, which is particularly useful in admin scenarios.