Halloween Sale 15% off Ends in See the plans
PHP

MemberPress: Show Menu Items Only to Certain Memberships

Hides navigation menu items from people who don't hold a given MemberPress membership, using a CSS class like wpide-mepr-123 on the menu item.

Don’t have WPIDE yet? Install it on your site

Code

if ( ! class_exists( 'MeprUser' ) ) {
    return;
}

add_filter( 'wp_nav_menu_objects', function ( $items ) {
    $member  = is_user_logged_in() ? new MeprUser( get_current_user_id() ) : null;
    $removed = array();

    foreach ( $items as $key => $item ) {
        $wanted = array();

        foreach ( (array) $item->classes as $class ) {
            if ( preg_match( '/^wpide-mepr-(\d+)$/', $class, $m ) ) {
                $wanted[] = (int) $m[1];
            }
        }

        $hide = in_array( (int) $item->menu_item_parent, $removed, true );

        if ( $wanted && ! current_user_can( 'manage_options' ) ) {
            $allowed = false;

            foreach ( $wanted as $membership_id ) {
                if ( $member && $member->is_already_subscribed_to( $membership_id ) ) {
                    $allowed = true;
                    break;
                }
            }

            $hide = $hide || ! $allowed;
        }

        if ( $hide ) {
            $removed[] = (int) $item->ID;
            unset( $items[ $key ] );
        }
    }

    return $items;
} );

Notes

Enable "CSS Classes" under Screen Options in Appearance > Menus, then add wpide-mepr-{membership ID}. Several classes mean "any of these".

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.