我正在尝试为WooCommerce制作一个简单的折扣代码,在购买前为您提供百分比的折扣。可以说,如果您添加价值100美元的产品,您将获得2%的折扣,如果您添加价值250美元的产品,您将获得4%的折扣,等等。
我唯一发现的是:
// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
/**
* Add custom fee if more than three article
* @param WC_Cart $cart
*/
function add_custom_fees( WC_Cart $cart ){
if( $cart->cart_contents_count < 3 ){
return;
}
// Calculate the amount to reduce
$discount = $cart->subtotal * 0.1;
$cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}
,但无法设法使其与价格合适的修改钩子一起使用。
我该如何实现?
这是一种使用基于卡车小计的税额的条件来进行此过程的方法,以将此渐进百分比添加为负费用,因此折扣:
add_action( 'woocommerce_cart_calculate_fees','cart_price_progressive_discount' );
function cart_price_progressive_discount() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$has_discount = false;
$stotal_ext = WC()->cart->subtotal_ex_tax;
// Discount percent based on cart amount conditions
if( $stotal_ext >= 100 && $stotal_ext < 250 ) {
$percent = -0.02;
$percent_text = ' 2%';
$has_discount =true;
} elseif( $stotal_ext >= 250 ) {
$percent = -0.04;
$percent_text = ' 4%';
$has_discount =true;
}
// Calculation
$discount = $stotal_ext * $percent;
// Displayed text
$discount_text = __('Discount', 'woocommerce') . $percent_text;
if( $has_discount ) {
WC()->cart->add_fee( $discount_text, $discount, false );
}
// Last argument in add fee method enable tax on calculation if "true"
}
这在您的活动子主题(或主题)或任何插件文件中的function.php文件中。
此代码已测试并有效。
类似:WooCommerce-基于购物车数量的有条件渐进式折扣
参考:WooCommerce类-WC_CART -ADD_FEE()方法