Paid Memberships Pro: Show Menu Items Only to Certain Levels
Hides navigation menu items from anyone who doesn't hold a matching membership level, using a CSS class like wpide-level-2 on the item.
Opens WPIDE on
Code
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) ) {
return;
}
add_filter( 'wp_nav_menu_objects', function ( $items ) {
$removed = array();
foreach ( $items as $key => $item ) {
$wanted = array();
foreach ( (array) $item->classes as $class ) {
if ( 'wpide-level-any' === $class ) {
$wanted[] = 'any';
} elseif ( preg_match( '/^wpide-level-(\d+)$/', $class, $m ) ) {
$wanted[] = (int) $m[1];
}
}
$hide = in_array( (int) $item->menu_item_parent, $removed, true );
if ( $wanted && ! current_user_can( 'manage_options' ) ) {
$levels = in_array( 'any', $wanted, true ) ? null : array_filter( $wanted, 'is_int' );
$hide = $hide || ! pmpro_hasMembershipLevel( $levels );
}
if ( $hide ) {
$removed[] = (int) $item->ID;
unset( $items[ $key ] );
}
}
return $items;
} );
Notes
Enable "CSS Classes" under Screen Options in Appearance > Menus. Use wpide-level-any for "any level".
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.