Search code examples
phpwordpressvalidationwoocommercecart

WooCommerce cart validation: check that specific product is always added before other products


Description:

I have use case where I need to check if a specific product has been added to cart before customer adds another products to cart.

Background:

We are renting products out based on packages(which are products). Packages include multiple products and products do not have price, packages do. So basically you would need to add a package(with price) and products(with no price) to cart.

Problem:

At the moment customers can add products before packages and they can continue to shopping cart with total zero.

Some of the progress what I have:

if ( ! WC()->cart->is_empty() )
    foreach( WC()->cart->get_cart() as $cart_item )
    // now i would need to check if cart consists a package

And i could solve adding product to cart with no package in cart like this:

if (WC()->cart->is_empty() )
//then don't add product to cart, tell customer to add package first.

Solution

    • Use the woocommerce_add_to_cart_validation hook
    • Comment with explanation added in the code
    function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
        // Product (ID) in cart
        $product_first_in_cart = 30;
        
        // Compare
        if ( $product_first_in_cart != $product_id ) {
            // Set variable
            $in_cart = false;
            
            // Cart NOT empty
            if ( ! WC()->cart->is_empty() ) {
                // Loop trough cart
                foreach( WC()->cart->get_cart() as $cart_item ) {
                    // Search for the specific product
                    if ( $cart_item['data']->get_id() == $product_first_in_cart ) {
                        // Found, break loop
                        $in_cart = true;
                        break;
                    }
                }
            }
            
            // NOT in cart
            if ( ! $in_cart ) {
                wc_add_notice( __( 'Please add product "A" before adding other products', 'woocommerce' ), 'error' );
                $passed = false;
            }
        }
    
        return $passed;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );