Search code examples
phpwordpresswoocommerceproductcart

Limit orders to one product in WooCommerce allowing different variations of a variable product


I try to limit customers buy one product with woocommerce. I use this code:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
    global $woocommerce;
    $woocommerce->cart->empty_cart();

    return $cart_item_data;
}

The problem is that I can´t use two variations in the same variable product. I need something to limit one product per order but can allow customer to and multiple variations of the same variable product.

Example: Customer buy a samsung j7 smartphone in color Black and at the same time a samsung j7 in color blue. Now if customer want additionally to add a Sony Xperia smartphone he must do another order for it.

Any help is appreciated.


Solution

  • The following will restrict add to cart to allow only item from the same product (so for variable products, it will allow adding to cart different variations of the same variable product):

    add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
    function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = 0 ) {
        if( WC()->cart->is_empty() )
            return $passed;
    
        $product = wc_get_product($product_id);
        $items_in_cart = [];
    
        if ( $product && 'variable' !== $product->get_type() ) {
            $passed = false;
        } elseif ( $product && 'variable' === $product->get_type() ) {
            $items_in_cart[$product_id] = $product_id;
    
            // Loop through cart items
            foreach( WC()->cart->get_cart() as $cart_item ){
                $items_in_cart[$cart_item['product_id']] = $cart_item['product_id'];
            }
            if( count($items_in_cart) > 1 )
                $passed = false;
        }
    
        // Avoid add to cart and display an error notice
        if( ! $passed )
            wc_add_notice( __("Different items are not allowed on an order.", "woocommerce" ), 'error' );
    
        return $passed;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.