我正在编写一个用于修改价格的函数。
根据某些类别中产品的总价格,将应用折扣(-1至-4%)
该功能在购物车和迷你购物车上都可以正常使用,直到“订购”页面为止。但是折扣不应用于实际订单!
// hook :
add_action( 'woocommerce_before_calculate_totals', array($this,'action_woocommerce_before_calculate_totals'), 10 );
// function
function action_woocommerce_before_calculate_totals( $WC_Cart ) {
// 1. verifications... if eligible then proceed to :
// 2. sum up eligible products amounts
$eligible_items = array();
$total_eligible_price = 0;
foreach ( $WC_Cart->get_cart_contents() as $cart_item_key => $cart_item ) {
if(!isProductEligible($cart_item)) continue;
$eligible_items[$cart_item_key] = array(
'full_price' => $cart_item['data']->get_price(),
);
$total_eligible_price += $cart_item['data']->get_price() * $cart_item['quantity'];
}
// 3. find the correct ratio
$price_ratio_to_apply = getPriceRatioForTotal($total_eligible_price);
// 4. and calculate the discounted price for eligible items
foreach($eligible_items as $item_key => $item) {
$eligible_items[$item_key]['discounted_price'] = $item['full_price'] * $price_ratio_to_apply;
}
// 5 then apply discounted prices to cart items
foreach($WC_Cart->get_cart() as $cart_item_key => $cart_item ) {
if(!isset($eligible_items[$cart_item_key])) continue;
$discounted_price = $eligible_items[$cart_item_key]['discounted_price'];
$cart_item['data']->set_price( $discounted_price );
}
该功能在购物车页面和订单页面上完美工作(其他功能用于在购物车项目行上显示全价/折扣价)
但是,当客户实际验证订单时,对订单不执行任何操作。
在验证订单时,我还应该添加另一个挂钩以应用折扣价吗?
答案 0 :(得分:0)
我认为您应该尝试执行以下一项操作:
do_action( 'woocommerce_checkout_create_order_line_item', $item, $cart_item_key, $values, $order );
或
do_action( 'woocommerce_checkout_create_order', $order, $data );
这将在创建和保存价格之前更新价格。
但是我必须说,我认为动态地应用优惠券会更好。这样,您将在订单上看到折扣,这将对您和您的客户都非常方便。