Site icon WP Smith

Using Custom Menus to Create Custom Menus Based on Role/Capabilities

So thanks to Nathan Rice (@nathanrice), creator of Genesis, I was able to complete my code to create menus based on user roles and capabilities. On one of my sites, the user wanted to display three different menus based on one's user roles and capabilities:

  1. One to display if a person was a Contributor or higher (read, edit posts, etc.).
  2. One to display if a person was a Subscribor (read)
  3. One to display for a visitor (none)

So as I stumbled through the code, here is the final code for Genesis Users. For non-Genesis users simply change 'menu_class' => genesis_get_option('nav_superfish') ? 'nav superfish' : 'nav', to 'menu_class' => '',. And you will need to change the add_action and remove_action code.

[php]//Custom Menu Based on Roles/Capabilities
remove_action('genesis_after_header', 'genesis_do_nav');
add_action('genesis_after_header', 'custom_genesis_do_nav');
function custom_genesis_do_nav() {

if ( current_user_can('edit_posts') ) {
$nav = wp_nav_menu(array(
'theme_location' => 'primary',
'menu' => 1,
'container' => '',
'menu_class' => genesis_get_option('nav_superfish') ? 'nav superfish' : 'nav',
'echo' => 0
));
printf( '<div id="nav"><div class="wrap">%s</div></div>', $nav );
}
elseif ( current_user_can('read') && !current_user_can('edit_posts') ) {
$nav = wp_nav_menu(array(
'theme_location' => 'primary',
'menu' => 2,
'container' => '',
'menu_class' => genesis_get_option('nav_superfish') ? 'nav superfish' : 'nav',
'echo' => 0
));
printf( '<div id="nav"><div class="wrap">%s</div></div>', $nav );
}
elseif(!current_user_can('read') && !current_user_can('edit_posts') ) {
$nav = wp_nav_menu(array(
'theme_location' => 'primary',
'menu' => 3,
'container' => '',
'menu_class' => genesis_get_option('nav_superfish') ? 'nav superfish' : 'nav',
'echo' => 0
));
printf( '<div id="nav"><div class="wrap">%s</div></div>', $nav );

}
else //just in case
{
genesis_do_nav();
}

} [/php]

To get the menu id number, simply go to Appearance > Menus. When you mouse over the menus, you should see a URL like http://mydomain.com/wp-admin/nav-menus.php?action=edit&menu=44. The menu=44 is your menu ID. When you click on them the URL should appear in the address bar if you cannot see the URLs in the status bar.