Woocommerce sell rules

Question

I created this function to give precise purchase rules to a product category (food) in woocommerce.

This function allows you to purchase only a specific number of products (5,12,24,36)

But now I have a problem. I want to sell a product that can also be purchased alone (1,2,3,4)

I created a new category (merchandising) But it seems that the rule used for (food) applies to all categories.

How can I exclude the merchandising category from the rule (5,12,24,36)?

I attach code:

Thanks

<?php
function checkout_validate() {

    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {

        //Count of "food" items quantity
        $food_item_quantity = 0;

        // Get number of items in the cart. OLD VERSION
        //$items_in_cart = WC()->cart->get_cart_contents_count();

        //get items in cart
        $items = WC()->cart->get_cart();
        // Allowed amounts
        $allowed_amounts = array(5, 12, 24, 36);

        //Allowed parent cat
        $food_parent_cat_id = 152;
    
        //Check all items in cart
        foreach($items as $item => $values) {
            $current_item_is_food = false;
            $product_id =  $values['product_id']; //get product id
            $product_terms = get_the_terms( $product_id, 'product_cat' ); //get product terms
            foreach($product_terms as $term) {
                $parent_cat_id = ($term->parent == 0) ? $term->term_id : $term->parent; //get parent term
                if ($parent_cat_id == $food_parent_cat_id) {
                    $current_item_is_food = true;
                }
            }
            //if product is "food" sum its quantity to the food counter
            if ($current_item_is_food) {
                $food_item_quantity = $food_item_quantity + $values['quantity'];
            }
        }

        // If items in cart NOT equal to allowed amounts, show error message
        if ( !in_array( $food_item_quantity, $allowed_amounts)) {
            wc_add_notice( __( 'Devi raggiungere la quantita di 5, 12, 24 o 36 pasti (escluse barrette e gift card) per comporre il tuo box. Attualmente hai ' . $food_item_quantity . ' pasti nel tuo carrello.', 'woocommerce' ), 'error' );
            remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
        } else {

            $new_method = get_field('metodo_calcolo_tempistiche_spedizione', 'options');
            if ($new_method) {
                hw_calc_and_show_shipping_day_new();
            } else {
                hw_calc_and_show_shipping_day();
            }
        }
    }
}
add_action( 'woocommerce_check_cart_items' , 'checkout_validate' );

0
rafa 2 months 0 Answers 10 views 0

Leave an answer