Pages

Oct 7, 2022

Check if cart contains only one product of a perticular category

 

You can search entire cart and checks if it contains only one product of a particular category.

Here suppose your category slug is 'your-category-slug'


Here is a simple function you can place this in your plugin or theme function file


function check_category_alone_in_cart( $category ) {

        

    // check each cart item for our category

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        

        // if a product is not in our category, bail out since we know the category is not alone

        if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {

            return false;

        }

    }

        

    // if we're here, all items in the cart are in our category

    return true;

}



function chk_wc_prevent_checkout_for_category() {

    //  If the cart is empty, then let's hit the ejector seat

    

    if (WC()->cart->is_empty()) {

        return;

    }       


    // set the slug of the category for which we disallow checkout

    $category = 'your-category-slug';

    

    // get the product category

    $product_cat = get_term_by( 'slug', $category, 'product_cat' );

    

    // sanity check to prevent fatals if the term doesn't exist

    if ( is_wp_error( $product_cat ) ) {

        return;

    }

    

    // check if this category is the only thing in the cart

    if ( check_category_alone_in_cart( $category ) ) {

        

        // render a notice to explain why checkout is blocked

        wc_add_notice(  'Cart contains the product which has category "your-category-slug" !!! ', 'error' );

return false;

    }  

return true;

}


add_action( 'woocommerce_check_cart_items', 'chk_wc_prevent_checkout_for_category' );