2

I am trying to update cart item prices. Without double loop. Currently using:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) 

and:

$cart_item['data']->set_price( 0 );

I would like to change per item price based on number of items in the cart. for example if the person adds 5 items for 1$ each. on the 6th item I would like to change the price for all the items to .90 cents.

currently I am doing this in a double loop. first loop counts all the items and then the second sets the price based on the number of items.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Thisisnuts
  • 49
  • 6
  • Please edit your post to include an actual question. Because it sounds like you currently have everything figured out. – DHerls Jul 03 '20 at 19:01

1 Answers1

0

add_action('woocommerce_before_calculate_totals', function() {

  // This is necessary for WC 3.0+
  if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

  // Avoiding hook repetition (when using price calculations for example)
  if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

  global $woocommerce;

  //echo $woocommerce->cart->get_cart_total();
  $count = $woocommerce->cart->cart_contents_count; 

  if ($count >= 6) {
    foreach ( WC()->cart->get_cart() as $item ) {
      $item['data']->set_price(0.90);
    }
  } else {
    foreach ( WC()->cart->get_cart() as $item ) {
      //$item['data']->set_price(1.00);
      $item['data']->set_price( wc_get_price_excluding_tax( $item['data'] ) );
      // $item['data']->set_price( wc_get_price_including_tax( $item['data'] ) );
    }
  }
}, 20, 1);
Ruudi
  • 124
  • 7