We can create an unlimited number of menus in the WordPress menu section and assign them to different menu locations in the theme. In this scenario, we wanted to change the top menu for different user types and show different menu items. So, we created three menus called WPCookbookMenu1, WPCookbookMenu2, and WPCookbookMenu3.
The menu of the Twenty Twenty theme is loaded from the header.php template. So, we copied the template into the TwentyTwenty Child theme folder with the same path. Then, we removed the existing menu generation code and added custom code to include the conditional checks.
In the first part of the code, we created an array to store user roles and a menu name to display the respective user role. Next, we used a foreach loop to traverse through the array and check the permission level of the current user with the current_user_can function. Once a match was found, we changed $menu_name to a role-specific menu while keeping WPCookbookMenu3 as the default value for $menu_name. The last part of the code is the same as the original code in the Twenty Nineteen theme, except for the addition of the 'menu' => $menu_name parameter and the removal of the theme_location parameter from the wp_nav_menu function.
The menu name changes based on the user role, which is used to conditionally display the menu. When a matching user role is not found, it will display the WPCookbookMenu3 menu for guests and logged in users with other roles.
Before moving on to the next recipe, replace the header.php file inside the child theme folder with the original file from the Twenty Twenty theme. We're doing this since we want to use the original theme for the next recipe.