这可能是一个菜鸟问题,所以提前道歉。
我有可变的订阅产品,其价格因订阅长度而异。我还有 subscription_length = 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 个订阅。如果我偏离了切线,我愿意接受不同的方法。
终于解决了问题。没有“subscription_length”的设置器。必须使用 update_meta_data 方法。元键是“_subscription_length”。以下代码有效。
function csi_align_subscription_length( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$maxlength = (float) 0;
// Find the longest subscription length
foreach ( $cart->get_cart() as $cart_item ){
if ( is_a( $cart_item['data'], 'WC_Product_Subscription' ) || is_a( $cart_item['data'], 'WC_Product_Subscription_Variation' ) ) {
$length = (float) WC_Subscriptions_Product::get_length( $cart_item['data'] );
$maxlength = ($length > $maxlength) ? $length : $maxlength ; //get the longest length
}
}
// set the subscription length for everything in the cart
foreach ( $cart->get_cart() as $item_key => $cart_item ){
if ( is_a( $cart_item['data'], 'WC_Product_Subscription' ) || is_a( $cart_item['data'], 'WC_Product_Subscription_Variation' )) {
$cart_item['data']->update_meta_data( '_subscription_length', $maxlength );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'csi_align_subscription_length', 5, 1 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)