dsdt66064367 2018-11-28 14:19
浏览 87
已采纳

在woocommerce中设置购物车数量与foreach无限循环

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?

  • 写回答

1条回答 默认 最新

  • doupai8095 2018-11-29 02:16
    关注

    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 ) {
            $cart->set_quantity( $cart_item_key, 42 );
        }
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失