【发布时间】:2021-06-28 03:10:59
【问题描述】:
我正在尝试使用 woocommerce_after_calculate_totals 和 woocommerce_before_calculate_totals 挂钩将购物车的总金额 ($GetTotalPrice) 从函数 cart_prices_GetPrice() 传递给函数 cart_prices_ApplyPrice(),但我得到一个空值。
//Trying to get cart amount
add_action('woocommerce_after_calculate_totals', 'cart_prices_GetPrice');
function cart_prices_GetPrice() {
//Getting the cart amount
$GetTotalPrice = WC()->cart->get_cart_total();
return $GetTotalPrice;
}
//Applying custom price
add_action('woocommerce_before_calculate_totals', 'cart_prices_ApplyPrice');
function cart_prices_ApplyPrice( $cart_object ) {
//Getting the cart amount from first function
$totalprice = cart_prices_GetPrice(); // doesn't work and returns 0 :(
//price change to cost2
if( $totalprice != 0 && $totalprice >= 2000 ) {
foreach ( $cart_object->get_cart() as $cart_id => $cart_item ) {
// get products id
$product_id = $cart_item['product_id'];
if( $cart_item['product_id'] == $product_id ) {
// price change to cost2
$new_price1 = 0.20;
$cart_item['data']->set_price( $new_price1 );
}
}
}
}
同时,每个功能单独工作完美。
我究竟做错了什么?是否有可能以某种方式链接两个钩子数据,以便第一个不返回空值?
更新:
我将无法拒绝钩子woocommerce_before_calculate_totals,因为我需要为购物车中的每个产品单独申请降价。
【问题讨论】:
-
@LoicTheAztec 感谢您的好建议,但在这种情况下,搜索购物车中每件商品的产品 ID 将不起作用。我需要为购物车中的每件商品单独降价。
标签: php wordpress woocommerce cart hook-woocommerce