In woocommerce I am trying to avoid proceed to checkout when cart items are from mixed product categories… The following code is mostly working as I intended:
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category that cannot be mixed from other categories
$category = 'test';
// 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;
}
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
//Proceed to checkout
}
else { // otherwise post a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'hi there! looks like your cart contains products from PREORDER and ONHAND categories, in order to proceed go to cart and dont mixed it.', $category_name ), 'error' ); }
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
function sv_wc_is_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;
}
But I have a problem: When cart contain items only from other product categories it doesn't allow proceed to checkout displaying the error message.
To resume:
- If the cart contains "TEST" product category: Allow "proceed to checkout" (working)
- If the cart items have mixed product categories ("TEST" and others): NOT allow "proceed to checkout" and display the error message (working)
- If the cart contains only other product categories (without the "TEST" product category): NOT allow "proceed to checkout" and display the error message (NOT WORKING)
How can I make it work for other product categories, allowing "proceed to checkout"?
Any help is appreciated.