I tried to show the navigation menu based on user role in WordPress. I couldn’t really find what I need from Google. So I decided to modify the template directly.
- I need to create role for user. By default we can’t add new role in WordPress. So, I use Capability Manager Plugin to create new role with it’s capabilities. In this post, I create ‘Staff’ and ‘Client’ role. Then assign the new role to the user.
- Next, I create 4 different menus; ‘public’, ‘admin’, ‘client’, and ‘staff’ menu. And set the ‘public’ as the default menu.
- Open the header.php of the current theme, search for:
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
and then add the following code:
<?php
if (is_user_logged_in()) {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
switch ($user_role) {
case 'staff':
$menu = 'staff';
break;
case 'client':
$menu = 'client';
break;
case '':
$menu = 'main';
break;
}
wp_nav_menu( array( 'menu' => $menu, 'container_class' => 'menu-header', 'theme_location' => 'primary' ) );
}
?>
The code above just check what is the current user role and display the menu after the public menu based on the role. If it is public user, the default menu will be displayed.