Woocommerce Membership Limiting Members to One Membership

675 Views Asked by At

I have a Wordpress Memberships website that is built on WooCommerce with WooCommerce-Memberships plugin.

The scenario:

 - Membership Plan = Gold-Plan-Membership / 1-month

 - simple Product = Gold-Product-Membership / €10,00

When the customer buys the product "Gold-Product-Membership" activates the subscription "Gold-Plan-Membership" for 1 month. and so far so good.

I want to limit members to only one active membership at a time. What I want to do is block creating any new membership from purchase if any other membership is active.

Now. The following code check for active customer membership plans and their status ('active', 'complimentary', 'pending', 'free_trial'), and Memberships will not create a new user membership for this order. The following code will check for all membership statuses that have access to restricted content.

But only check the Membership Plan, not the purchase of its product.

I'll explain. The customer purchases the product "Gold-Product-Membership", finishes the checkout procedure and actually executes the payment, the order for that product is processed. While actually the "Gold-Plan-Membership" is not activated.

It is clear that this is a problem.

I'm looking for a solution that works on the product but at the same time integrates with its relationship to the Membership-Plan status.

  • I want to limit members to only one active membership at a time.

Thanks in advance

The Code

/**
 * There are two ways we could prevent purchasing more than one membership:
 *  1. prevent access if the customer already has an active membership
 *  2. prevent access if the customer already has any membership
 *
 * This snippet shows the second scenario.
 */


/**
 * Do not grant membership access to purchasers if they already hold any membership, regardless of status
 *
 * @param bool $grant_access true if the purchaser should get memberships access from this order
 * @param array $args {
 *  @type int $user_id purchaser's WordPress user ID
 *  @type int $product_id the ID of the access-granting product
 *  @type int $order_id the ID of order for this purchase
 * }
 * @return bool $grant_access
 */

function sv_wc_memberships_limit_to_one_membership( $grant_access, $args ) {

    // get all active memberships for the purchaser, regardless of status
    $memberships = wc_memberships_get_user_memberships( $args['user_id'] );

    // if there are any memberships returned, do not grant access from purchase
    if ( ! empty( $memberships ) ) {
        return false;
    }

    return $grant_access;
}
add_filter( 'wc_memberships_grant_access_from_new_purchase', 'sv_wc_memberships_limit_to_one_membership', 1, 2 );
0

There are 0 best solutions below