Allow only one variation of a product to be added to cart -WooCommerce

Oct 14, 2019

If you have a Product in your WooCommerce for which only one variation of the product can be added in the cart , you can use this simple snippet to get that going.

 * @snippet       WooCommerce Varitaion Sold Individually
 * @author        Naveen Yellamaddi
 * @compatible    WooCommerce 3.7.0

add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );

function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {

    $product_a = 14576;
    $product_b = 14091;

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $cart_product_id = $cart_item['product_id'];
        if ($cart_item['variation_id']) {
            $cart_product_id = $cart_item['variation_id'];

        if ( ($cart_product_id == $product_a && $variation_id == $product_b) || ($cart_product_id == $product_b && $variation_id == $product_a) ) {

            wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
            $passed = false; // don't add the new product to the cart
            // We stop the loop

    return $passed;

Here product_a is the product id and product_b is the variation id.

If you want to make all variations of a single product want to be purchased alone you can use this plugin

You can use this snippet to enable sold alone for only a particular variation of a product to be sold alone.

How to add this snippet?

You can add this snippet to your child themes functions.php , We don't recommend adding code to your main theme if its not developed by you. Otherwise you can use a simple plugin

Express your views in the comment section below.

Yellamaddi Naveen

Naveen is 22 years old , self-taught Wordpress developer , Currently Working as a Wordpress developer at Upwork.