【发布时间】:2019-09-19 08:31:38
【问题描述】:
这可能是一个菜鸟问题,所以提前道歉。
我有可变订阅产品,其价格因订阅长度而异。我也有订阅长度 = 0 的简单订阅。当购物车包含这两种类型时,Woocommerce 订阅会创建两个订阅。
我正在尝试修改购物车中所有商品的 subscription_length 元数据以匹配购物车中的最长长度,因此只会创建一个订阅。
我似乎无法找到更新购物车的正确方法。这可能只是愚蠢的人类 PHP 技巧。
这是该语句的最新变体,但现在不起作用:
$cart[$item_key]['data']->subscription_length = $maxlength;
我已经尝试了十几个或更多主题的变体来更新 $cart 数据。有些失败,有些成功,但 $cart 中的数据没有改变。
function csi_align_subscription_length() {
$maxlength = 0;
$cart = WC()->cart->get_cart();
//find the longest length
foreach ( $cart as $item_key => $item ){
if ( WC_Subscriptions_Product::is_subscription( $item['data'] ) ) {
$length = WC_Subscriptions_Product::get_length( $item['data'] );
$maxlength = ($length > $maxlength) ? $length : $maxlength ; //get the longest length
}
}
//set all subscription lengths to the longest lengths
foreach ( $cart as $item_key => $item ){
if ( WC_Subscriptions_Product::is_subscription( $item['data'] ) ) {
echo '<pre>';
echo "cart-item before: ". var_dump($cart[$item_key]);
$cart[$item_key]['data']->subscription_length = $maxlength;
echo "cart-item after: ".var_dump($cart[$item_key]);
echo '</pre>';
}
}
WC()->cart->set_cart_contents($cart);
}
add_filter( 'woocommerce_subscription_cart_before_grouping', 'csi_align_subscription_length', 10, 1 );
我只需要将购物车中的订阅与一个公共组对齐,因此每次结帐时我只有 1 个订单和 1 个订阅。如果我迷失在切线上,我愿意采用不同的方法。
【问题讨论】:
标签: php methods woocommerce cart woocommerce-subscriptions