【发布时间】:2017-08-07 10:01:20
【问题描述】:
我有一家商店,如果批量购买产品,我们会打折(批量优惠因产品而异)。该部分已排序。
目前,我使用这样的负费用申请折扣:
function sale_custom_price($cart_object) {
foreach ($cart_object->cart_contents as $p) {
$prod_id = $p['product_id'];
$prod_n = $p['quantity'];
$prod_price = $p['data']->price;
$prod_name = $p['data']->post->post_title;
$prod_total = $p['line_total'];
/*
calc_discount: NULL for no discount for this product
else
array(
n => how many are required, e.g. 12
free_pcs_deal => how many of these should be free, e.g. 1
)
*/
$discount = calc_discount($prod_id, $prod_n);
if (is_null($discount)) {
continue;
}
$discount_n = $discount['n'];
$free_pcs_deal = $discount['free_pcs_deal'];
if ($discount_n <= 0) {
continue;
}
$discount_txt = $prod_name . ' (' . $discount_n . ' x ' . $free_pcs_deal . ' stk.)';
$discount = -1 * $discount_n * $free_pcs_deal * $prod_price;
$cart_object->add_fee('Rabat: ' . $discount_txt, $discount, true, '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'sale_custom_price', 2, 1);
但这不受支持,并且在未来将变得不可能。因此,我想自动调整产品价格。
假设客户购买了12件产品A,正常价格是100,但是产品A有大宗交易买12,只付11(买11送1)。所以目前,产品价格为 12*100 = 1200,负费用为 100。所以所有 12 种产品 A 的平均产品价格为 11*100/12 = 91.67。我希望将其用于我的购物车。
但我无法让它在购物车中显示修改后的价格以及正确的 line_total 和 line_subtotal 以及订单总额。所以好像没找到合适的action/filter。
我尝试过这样的事情:
$cart = WC()->cart->cart_contents;
foreach ($cart as $key => $p) {
$custom_price = 111; // of course replaced by logic calculating the new, modified price
WC()->cart->cart_contents[$key]['data']->price = $custom_price;
}
我已经在woocommerce_cart_updated、woocommerce_before_cart_contents、woocommerce_add_to_cart 和其他人中尝试过这种逻辑,但它不会显示正确的购物车以及更新的价格、line_total、订单总数等。
我可以通过woocommerce_cart_item_price钩子计算并显示更新后的价格,但这只是显示,不在业务逻辑中,所以所有总计都被修改了。
我做错了什么?
【问题讨论】:
标签: woocommerce hook-woocommerce