在WooCommerce中,我想在不使用优惠券的情况下进行折扣,折扣的计算将基于产品价格,比如“以3种产品为价格2。
在我的活动主题的function.php中,我使用以下代码:
function promo () {
if (is_cart()) {
$woocommerce->cart->add_fee( __('des', 'woocommerce'), -50.00`enter code here`, true, '');
}
}
add_action ('woocommerce_cart_calculate_fees', 'promo');我的问题是:这个代码不适用于结帐页面。
如果我强制执行检查顺序,折扣就会出现,但是总价值不会改变。我认为这不能节省费用。
我如何使它工作(在结帐页面)?
谢谢
发布于 2017-02-01 01:53:34
这个钩子是为购物车的费用(或折扣)而做的,所以你必须去掉
if (is_cart()) {条件,,这是为什么它不能工作的…。
以下是正确的功能代码,以实现“购买2分3”的折扣,这将根据行项目数量进行折扣:
add_action('woocommerce_cart_calculate_fees' , 'discount_2_for_3', 10, 1);
function discount_2_for_3( $cart_object ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising variable
$discount = 0;
// Iterating through cart items
foreach( $cart_object->get_cart() as $cart_item ){
// Getting item data from cart object
$item_id = $cart_item['product_id']; // Item Id or product ID
$item_qty = $cart_item['quantity']; // Item Quantity
$product_price = $cart_item['data']->price; // Product price
$line_total = $cart_item['line_total']; // Price x Quantity total line item
// THE DISCOUNT CALCULATION
if($item_qty >= 3){
// For each item quantity step of 3 we add 1 to $qty_discount
for($qty_x3 = 3, $qty_discount = 0; $qty_x3 <= $item_qty; $qty_x3 += 3, $qty_discount++);
$discount -= $qty_discount * $product_price;
}
}
// Applied discount "2 for 3"
if( $discount != 0 ){
// Note: Last argument is related to applying the tax (false by default)
$cart_object->add_fee( __('Des 2 for 3', 'woocommerce'), $discount, false);
}
}这将适用于简单的产品,但不适用于产品变体…。
代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。
代码经过测试和工作。
https://stackoverflow.com/questions/41965606
复制相似问题