0

我正在尝试使用以下代码以编程方式设置我的 Woocommerce 购物车中当前的商品数量(我在这里输入了数字 42 作为测试 - 一旦停止行为不端,动态值就会进入)。

我正在使用的代码如下:

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 );

一切都很好,直到我添加了“$cart->set_quantity($item_key, 42);”行 这会引发“致命错误:未捕获的错误:达到'256'的最大函数嵌套级别,正在中止!” 错误。出于某种原因,添加这条线似乎使它无限循环。

$cart 的 var_dump() 返回一个对象,包括 public 'cart_contents' (我想要获取的位)、public 'removed_cart_contents'、public 'applied_coupons' 等等。我的直觉是,它正在尝试更新所有这些的数量,而不仅仅是 cart_contents。如果是这种情况,有没有办法隔离购物车内容并返回这些内容。https://docs.woocommerce.com/wc-apidocs/class-WC_Cart.html建议 get_cart_contents() 应该这样做,但显然不是。

有什么明显的我做错了吗?

4

1 回答 1

2

您的代码中有一些错误和缺失的部分。尝试这个:

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 );
    }
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

于 2018-11-29T02:16:51.330 回答