Show Menu Items by Login Status or Role
Lets you hide individual menu items from guests, members or certain roles by giving them a CSS class such as wpide-logged-in, wpide-logged-out or wpide-role-editor.
Opens WPIDE on
Code
add_filter( 'wp_nav_menu_objects', function ( $items ) {
$logged_in = is_user_logged_in();
$roles = $logged_in ? (array) wp_get_current_user()->roles : array();
$removed = array();
foreach ( $items as $key => $item ) {
$classes = (array) $item->classes;
$hide = in_array( (int) $item->menu_item_parent, $removed, true );
if ( in_array( 'wpide-logged-in', $classes, true ) && ! $logged_in ) {
$hide = true;
}
if ( in_array( 'wpide-logged-out', $classes, true ) && $logged_in ) {
$hide = true;
}
$role_classes = preg_grep( '/^wpide-role-/', $classes );
if ( $role_classes ) {
$wanted = array_map( function ( $class ) {
return substr( $class, 11 );
}, $role_classes );
if ( ! array_intersect( $wanted, $roles ) && ! current_user_can( 'manage_options' ) ) {
$hide = true;
}
}
if ( $hide ) {
$removed[] = (int) $item->ID;
unset( $items[ $key ] );
}
}
return $items;
}, 10 );
Notes
Turn on "CSS Classes" under Screen Options in Appearance > Menus to add the classes. Child items of a hidden item are hidden too.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.