Stef
Stef

Reputation: 369

Infinite loop while setting cart quantity with foreach in woocommerce

I'm trying to programmatically set the quantity of items currently in my Woocommerce cart using the following code (I've entered the number 42 here as a test - dynamic value will go in once it stops misbehaving).

The code I'm using is as follows:

function update_quantity_in_cart( $cart ) {

if( ! is_cart() ) {
return;
}  

// Iterate through each cart item
foreach( $cart->get_cart_contents() as $item_key=>$cart_item ) {
  var_dump($cart);

  if ( isset( $cart_item['quantity'] )){
    $cart->set_quantity( $item_key, 42 ); // I think this line is causing the problem
  }
} // end foreach 
}

add_action( 'woocommerce_before_calculate_totals', 'update_quantity_in_cart', 5, 1 );

Everything is good until I add the line "$cart->set_quantity( $item_key, 42 );" which throws up a "Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting!" error. For some reason adding this line seems to make it keep looping infinitely.

A var_dump() for $cart returns an object including public 'cart_contents' (the bit I'm trying to get), public 'removed_cart_contents', public 'applied_coupons' and more besides. My instinct is that it's trying to update the quantity for all of these as opposed to just cart_contents. If that's the case, is there a way of isolating cart contents and just returning those. https://docs.woocommerce.com/wc-apidocs/class-WC_Cart.html suggests get_cart_contents() should do it but apparently not.

Anything obvious I'm doing wrong here?

Upvotes: 0

Views: 1035

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254373

There is some mistakes and missing parts in your code. Try this:

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( $cart_item['quantity'] != 42 )
            $cart->set_quantity( $cart_item_key, 42 );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.

Upvotes: 3

Related Questions