Home / Archive / MemberPress: Restrict Purchase of a Specific Membership Based on Existing Subscriptions
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Restrict Purchase of a Specific Membership Based on Existing Subscriptions

This code snippet restricts the purchase of a specified MemberPress membership (restricted membership), based on a user's existing active memberships. While on the MemberPress account page, a user won’t be allowed to purchase a membership if there is an active subscription to any of the memberships specified in the code (allowed memberships).

The sample code will prevent a user from purchasing the restricted membership with the ID of 789 if that user is already subscribed to one of the allowed memberships, either with the ID of 123 or 456.

To change the Restricted membership, replace the 789 dummy ID with the actual membership ID.

Code Preview
php
<?php
add_filter( 'mepr-can-you-buy-me-override', function( $override, $product ) {
  // Check if the user is on the MemberPress Account page
  if ( !is_page( 'account' ) ) {
    return $override;
  }
  // Get the current user and their active memberships
  $user = MeprUtils::get_currentuserinfo();
  $products = $user->active_product_subscriptions( 'ids' ); // Get all active membership IDs
  // Define the list of allowed memberships
  $allowed_products = array( 123, 456 );
  // Check if the user has any of the allowed memberships and the product ID matches the restricted product
  foreach ( $allowed_products as $allowed_product ) {
    if ( in_array( $allowed_product, $products ) && $product->ID == 789 ) {
      return false; // Prevent the purchase
    }
  }
  return $override; // Return the original override status if conditions are not met
}, 10, 2 );

Comments

Add a Comment