K
K
Kirill Nikonov2020-11-15 16:28:25
WordPress
Kirill Nikonov, 2020-11-15 16:28:25

How to apply a discount to certain product categories on the WooCommerce order page depending on the delivery format?

The fact is that the customer asks for a 50% discount for "Pickup" - I already did this (I found a code here on Habré that applies a discount to all goods), but there is one more condition - this discount should not be applied to two categories goods.
5fb12b6394b95608417983.png
I tried going through each product in the order list and checking if it belongs to a certain category or not through various operators (is_category, in_category, has_term), but it didn't work. What am I doing wrong?
(id = 37 is the id of the Premium rolls category)

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 10, 1 );
function custom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
    
    $category_id = 37; // premium-rolls id
    $cats = hml_get_category_gender_line( $category_id );
    
    foreach ( $cart->get_cart() as $cart_item ){
        if (!has_term($cats, 'product_cat', $value['product_id'] )){
            $price = $cart_item['data']->get_price(); // Get the product price
            $new_price = $price-$price*50/100; // the calculation
            $cart_item['data']->set_price( $new_price ); // Set the new price
        }
        
    }
}
function hml_get_category_gender_line( $cat_parent ){
  // get_term_children() accepts integer ID only
  $line = get_term_children( (int) $cat_parent, 'product_cat');
  $line[] = $cat_parent;
  return $line;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2020-11-15
@pton

in the loop that applies the discount, check if the category belongs to through has_termand exclude this product from applying the discount.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question