【发布时间】:2016-12-14 06:19:22
【问题描述】:
我希望在 woocommerce 购物车中,客户将获得 20% 的折扣,但我想将折扣金额限制为 500 美元。
这在 WooCommerce 中可行吗?
谢谢。
【问题讨论】:
标签: php wordpress woocommerce cart discount
我希望在 woocommerce 购物车中,客户将获得 20% 的折扣,但我想将折扣金额限制为 500 美元。
这在 WooCommerce 中可行吗?
谢谢。
【问题讨论】:
标签: php wordpress woocommerce cart discount
这可以使用 woocommerce_cart_calculate_fees 钩子和 WC_cart 方法 add_fee() 轻松完成。然后,如果您使用负费用,它就会变成 DISCOUNT。
在此函数中,折扣是根据不含税的购物车小计计算的(您可以轻松地将其更改为含税的总计)。
代码如下:
add_action( 'woocommerce_cart_calculate_fees', 'custom_limited_discount', 10, 1 );
function custom_limited_discount($cart_object) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Here 20 % of discount
$discount_percent = 0.2;
// Here the max discounted amount
$max_discount = 500;
// Here are some different cart totals
$cart_subtotal_excl_tax = WC()->cart->subtotal_ex_tax;
$cart_subtotal = WC()->cart->subtotal;
$cart_total = WC()->cart->total;
$discount = 0;
// CALCULATION with subtotal excluding taxes
$calculation = $cart_subtotal_excl_tax * $discount_percent;
// Limiting the discount to $max_discount
if ( $calculation > $max_discount ) {
$discount -= $max_discount;
} else {
$discount -= $calculation;
}
$discount_text_output = __( 'Discount (20 %)', 'woocommerce' );
// Adding the discount
$cart_object->add_fee( $discount_text_output, $discount, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
此代码经过测试,功能齐全。
代码进入您的活动子主题(或主题)的 function.php 文件中。或者也可以在任何插件 php 文件中。
注意:
add_fee()方法中的最后一个参数与是否应用税收有关(真或假)。
【讨论】: