I building my ecommerce for sell wine with wordpress 4.2.2 and woocommerce 2.3.11.
I created a custom function for end the order only with bottles on multiple of 6.
Until this I don’t have any problem, but I have 2 categories with packages of 6 bottles, so I want to avoid that this 2 categories will count in the quantity total items cart.
I’m not expert with php so I try to create a function that check if the each item is inside the category and if belong to one package category, subtract one item.
This work good only if there is one item of this 2 categories, but if I add 2 packages on the cart, only one will be subtract.
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$total_products = WC()->cart->cart_contents_count;
$multiples = 6;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$prodotti = $values['data'];
$terms = get_the_terms ($prodotti->id, 'product_cat');
foreach ($terms as $term){
$categoria = $term->term_id;
}
if (($categoria == 169) || ($categoria == 152)) {
$pacchetti = $values ['quantity'];
$totale = ($total_products-$pacchetti);
} else {
$totale = $total_products;
}
}
echo $totale;
if ( ( $totale % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of 6 products', 'woocommerce'), $multiples ), 'error' );
}
Desired Counting:
Existing Counting
I’m open for every solution for make this works.
Thank you a lot!
Your code looks pretty good to me. I think the one thing you are missing is the
has_term()
function to more reliably test which products are in your two special categories.