Hide Members-Only Pages From Menus for Visitors
Removes menu links to posts and pages marked members-only (by the WPIDE "Members-Only Posts" snippet) or set to private, so visitors never see links they can't open.
Opens WPIDE on
Code
add_filter( 'wp_nav_menu_objects', function ( $items ) {
if ( is_user_logged_in() ) {
return $items;
}
$removed = array();
foreach ( $items as $key => $item ) {
$hide = in_array( (int) $item->menu_item_parent, $removed, true );
if ( ! $hide && 'post_type' === ( $item->type ?? '' ) && ! empty( $item->object_id ) ) {
$object_id = (int) $item->object_id;
$hide = 'private' === get_post_status( $object_id ) || (bool) get_post_meta( $object_id, '_wpide_members_only', true );
}
if ( $hide ) {
$removed[] = (int) $item->ID;
unset( $items[ $key ] );
}
}
return $items;
} );
Notes
Logged-in users still see every link; restrictions by role are checked by the members-only snippet itself when the page is opened.
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.