这可能是一个菜鸟问题,所以提前致歉。
我有可变订阅产品,其价格因订阅时长而异。我还有 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 );
我只需要让购物车中的订阅与一个公共(public)组保持一致,因此我每次结账时只有 1 个订单和 1 个订阅。如果我迷失了切线,我愿意采用不同的方法。
最佳答案
终于解决了这个问题。 “subscription_length”没有 setter 。必须使用 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 );
关于php - 结帐前更改购物车项目订阅属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924998/