E
E
ekrasova2020-06-04 00:40:45
WordPress
ekrasova, 2020-06-04 00:40:45

How to make a discount coupon for every 3 items in the cart?

Hello.
Please tell me how can I add the code below, which was found here, so that it works not only once for 3 products, but for each 3 (3,6,9,12 ..). Help me out, please, I've been struggling with this for a day now and nothing

add_action( 'woocommerce_cart_calculate_fees','hml_fee_one_plus_one', 10, 1 );
function hml_fee_one_plus_one( WC_Cart $cart_object ) {
  global $wpdb, $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; }
  
  $arr_cart = $cart_object->get_cart();
  if ( 0 == sizeof($arr_cart) ) { return; }
        
  	$count = 0;
    $min_price = 0;
    $category_id = 81; 
     // получаем список всех вложенных категорий включая родительскую
    $cats = hml_get_category_gender_line( $category_id );
    
 foreach( $arr_cart as $item_key => $value ) {
 if ( has_term($cats, 'product_cat', $value['product_id'] ) ) {
        $count += $value["quantity"];
        $product = $value['data'];
        $price = $product->get_price();
        if ( $price ) {	$prices[] = floatval($price); }
      }
    }
    
    $min_price = max( $min_price, min($prices) );
    
    if ( $count >= 3 && $min_price > 0 ) {
      $fee = -1 * $min_price;
      $cart_object->add_fee( __('Акция'), $fee );
    }
    
    //}   
}

function hml_get_category_gender_line( $cat_parent ){
  $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-06-04
@pton

You need to rebuild the prices array.
Now it contains the prices of all items in the cart. You need to collect an array of prices given the quantity of each item. those. if there are 2 items for a product, then the prices array should contain two records of the price of this product.
Further, everything is simple
- Sort prices in ascending order
- find the multiplicity of the number of three (number / 3)
- take the resulting number of elements from prices - this is your promotional amount.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question