0

I'm using the following code to limit products from one category in the cart.

add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_category_allowed', 20, 3 );
function only_one_product_category_allowed( $passed, $product_id, $quantity) {

    $term_slugs   = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'slugs') );

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

        if( ! has_term( $term_slugs, 'product_cat', $cart_item['product_id'] ) ){

            wc_add_notice( __('Only goods from ONE category allowed in cart'), 'error' );
            echo "<script type='text/javascript'>alert('Only goods from ONE category allowed in cart');</script>";

            return false;
        }
    }
    return $passed;
}

Could someone please let me know how I can change the number of categories allowed in the cart at once instead of just one? And I'd like to know how the error message can be shown using ajax. The current error message only shows when the page is refreshed.

Any help is appreciated!

Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.