How to check if current user has a specific user role

Posted on: April 22nd, 2024
By: Tadeo Martinez

Add these to create global functions that can be used anywhere on the website

function currentUser() {
	$user = get_userdata( get_current_user_id() );
	return $user;
}

function currentUserGates() {
	$role_slug = 'client_gates_enterprises';
	return $role_slug;
}

Add the following where you want to add the logic. This can be useful for locations where different content depending on the user needs to be displayed.

if ( currentUser() && in_array( currentUserGates(), currentUser()->roles ) ) {
    // The current user has the specified role
    wp_nav_menu(array(
        'menu' => 'Gates Menu',
        'menu_class'=>'menu list-unstyled mb-0 d-flex justify-content-end'
    ));
} else {
    // The current user does not have the specified role
    wp_nav_menu(array(
        'menu' => 'primary',
        'menu_class'=>'menu list-unstyled mb-0 d-flex justify-content-end'
    ));
}

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published. Required fields are marked *