Check user’s role in WordPress

/**
 * Checks user role. Can be current user or user by ID.
 *
 * @see     https://wpcodebook.com/snippets/check-users-role-in-wordpress/
 * @return  bool
 */
function is_user_role( $user_role, $user_id = 0 ) {
	$the_user = ( 0 == $user_id ) ? wp_get_current_user() : get_user_by( 'id', $user_id );
	if ( ! isset( $the_user->roles ) || empty( $the_user->roles ) ) {
		$the_user->roles = array( 'guest' );
	}
	return ( isset( $the_user->roles ) && is_array( $the_user->roles ) && in_array( $user_role, $the_user->roles ) );
}

No comments yet.

Leave a Reply