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 WPF RichTextBox格式化大量文本卡顿如何解决
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥15 pip install后修改模块路径,import失败,需要在哪里修改环境变量?
  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型