How to avoid mixing two specific categories on cart on Woocommerce?

Viewed 78

I have 5 categories on Woocommerce, but want to restrict two of them to not allow combination "Sale" ; "Breakfast"

The reason is that products on "Sale" category are allowed to ship on same day only while "Breakfast" category with 1 day minimum delivery, so they can not be combined or mixed on cart.

I have this code but is not working:

function get_product_top_level_category($prod_id) {

    $cat = get_the_terms( $prod_id, 'product_cat' );
    $return_array = array();

    foreach ($cat as $category) {
        if($category->parent == 0){
        $return_array[] = $category->term_id;
        }
    }
    return $return_array;
}

add_filter ( 'woocommerce_before_cart', 'restrict_cart_for_a_single_category' );
function restrict_cart_for_a_single_category() {
    global $woocommerce;
    $cart_contents    =  $woocommerce->cart->get_cart( );
    $cart_item_keys   =  array_keys ( $cart_contents );
    $cart_item_count  =  count ( $cart_item_keys );

    // Do nothing if the cart is empty or has only one item
    if ( ! $cart_contents || $cart_item_count == 1 ) {
            return null;
    }

    // Multiple Items in cart
    $categories_not_allowed_mixing = array(
        'sale',
        'breakfast'
    );

    $categories_found = array();

    // Now we check each subsequent items top-level parent category
    foreach ( $cart_item_keys as $key ) {
        $product_id            =  $cart_contents[$key]['product_id'];
        $product_top_category  =  get_product_top_level_category( $product_id );

        foreach ($product_top_category as $top_category) {
            $product_top_category_term  =  get_term ( $top_category, 'product_cat' );
            $product_top_category_name  =  $product_top_category_term->name;

            if(in_array($product_top_category_name, $categories_not_allowed_mixing)) {
                if(in_array($product_top_category_name, $categories_found)) {
                    // if category name is already in the array do nothing as multiples are allowed
                } else {
                    $categories_found[] = $product_top_category_name;
                    // check how many of the category 
                }
            }

            if ( count($categories_found) > 1 ) {
                    $woocommerce->cart->set_quantity ( $key, 0, true );
                    $restrict_categories  =  1;
            }
        }
    }

    // code to display the message or warning only once for any user
    if ( isset ( $restrict_categories ) ) {
            echo '<p class="woocommerce-error">No se permite combinar productos en promoción de martes y viernes con desayunos, debido a que nuestras promociones solo pueden ser programadas para el mismo día y los desayunos con 1 día mínimo de anticipación. </p>';
            //add your code for redirection here

    }
}

Thanks in advance!

0 Answers
Related