简体   繁体   中英

remove products of a category from the total count cart woocommerce

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:

屏幕1  - 右计数

Existing Counting

屏幕2  - 计数错误

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.

add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
    $total_products = WC()->cart->cart_contents_count;
    $multiples = 6;
    $totale = 0;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $prodotti = $values['data'];

        if( ! has_term( array( 169, 152 ), 'product_cat', $prodotti->id ) ){
            $totale += $values['quantity'];
        } 

    }
    echo $totale;
    if ( ( $totale % $multiples ) > 0 ){
        wc_add_notice( sprintf( __('You need to buy in multiples of %d products', 'your-textdomain'), $multiples ), 'error' );
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM