Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce: Enable only one purchase per subscription in all store

Is there a way to block logged in user from buy any product after the first purchase of any product?

I want to limit each subscription to buy only one product and then no more shops on any product, only with new subscription.

I found a filter that do almost what i need but limit only one per product,

add_filter('woocommerce_add_to_cart_validation','rei_woocommerce_add_to_cart_validation',20, 2);
function rei_woocommerce_add_to_cart_validation($valid, $product_id){
    $current_user = wp_get_current_user();
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id)) {
        wc_add_notice( __( 'Purchased', 'woocommerce' ), 'error' );
        $valid = false;
    }
    return $valid;
}

but i need to lock every other product after first purchase of a subscription.

Maybe the best way would be when user click to pay for the product at check out page (at this time he need to be logged in) and check if he already purchased any product before.. if yes, he cant pay, only with new subscription...

im ugly on coding.. could somebody help me with this???

like image 342
Willy Werlang Avatar asked Oct 20 '25 15:10

Willy Werlang


1 Answers

Here is a solution for one subscription per cart, or membership if you are using subscriptions as product. Wish I knew who to give credit to but I have had this one in my magic kit for a while.

/**
 * c.)
 * @return (bool)
 */
add_filter( 'woocommerce_add_to_cart_validation','wpso35381172_validate_block_one_sub', 10, 2 );
function wpso35381172_validate_block_one_sub( $valid, $product_id ) {
// Get the current product
$current_product = wc_get_product( $product_id );
// See if the current product user's are viewing is a subscription product
if ( $current_product instanceof WC_Product_Subscription || 
     $current_product instanceof WC_Product_Variable_Subscription ) {
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        // Loop through all products in the cart
        $_product = $values['data'];
        // Check if current item is a subscription type
        if( $_product instanceof WC_Product_Subscription || 
            $_product instanceof WC_Product_Subscription_Variation ) {
            // Display a notice and cancel the addition of item to cart
 wc_add_notice( "Only one Subscription or Membership plan can be purchased." );
                return false;
            }
        }
    }
    return $valid;
}

This works on WC 3.0+ and uses instances of the WCS_ class.

like image 113
tradesouthwest Avatar answered Oct 22 '25 03:10

tradesouthwest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!