WordPress Check User Role Function

WordPress usually has a built in function for just about everything—it’s just a matter of finding it. In our case, we needed a function to check if a logged in user had a certain role. If not, show them different content. As far as we could find, one didn’t already exist (as of WordPress 3.5).

So we decided to quickly whip one up and share with the WordPress community. We made it flexible enough to pass in a user id instead of assuming the user was already logged in. It’s also setup for WordPress 3.6 which will allow multiple roles per user (Trac ticket #17924).

/**
 * Checks if a particular user has a role. 
 * Returns true if a match was found.
 *
 * @param string $role Role name.
 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
 * @return bool
 */
function appthemes_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 );
}
 
 
// example use for the current user
if ( appthemes_check_user_role( 'customer' )
    _e( "You've got access dude!", 'appthemes' );
else
    _e( "Sorry man, no luck.", 'appthemes' );
 
 
 
// example use for a specific user
$user_id = 23;
 
if ( appthemes_check_user_role( 'customer', $user_id )
    _e( "You've got access dude!", 'appthemes' );
else
    _e( "Sorry man, no luck.", 'appthemes' );

Like this tutorial? Subscribe and get the latest tutorials delivered straight to your inbox or feed reader.

Your rating: none
Rating: 4.7 - 53 votes

Popular Add-ons

Fortumo SMS payment gateway

Fortumo sms payment gateway for ClassiPress


(3)
$39

AdPoster Blocker

A simple but powerful plugin that blocks spammy new user regs and/or…


(5)
$19

Listings by Category or Tag

Display listings by Category or Tag using a filter widget.


(1)
$12