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: 5
Rating: 4.7 - 53 votes

Popular Add-ons

Coups

A clean and advanced clipper child theme with extended features.


(10)
$39

CP-Tabber

Show specific custom fields as tabs on an ad detail page.


(3)
$12

AppThemes Coupons

Start offering coupons and promotions to your customers.


(15)
$29