Php 基于购物车金额的累进百分比折扣

Php 基于购物车金额的累进百分比折扣,php,wordpress,woocommerce,cart,discount,Php,Wordpress,Woocommerce,Cart,Discount,我正在尝试为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

我正在尝试为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);
}
//计算费用前钩住
添加操作(“woocommerce\u cart\u calculate\u fees”、“添加\u custom\u fees”);
/**
*如果超过三篇文章,则添加自定义费用
*@param WC_Cart$Cart
*/
功能添加自定义费用(WC\U购物车$Cart){
如果($cart->cart\u contents\u count<3){
返回;
}
//计算要减少的金额
$折扣=$购物车->小计*0.1;
$cart->add_fee('您的购物车中有3个以上的商品,已添加10%的折扣',-$折扣);
}
但无法通过修改钩子使其工作,而这些钩子是为了价格


如何实现这一点?

以下是使用基于购物车小计(不含税金额)的条件将此累进百分比添加为负费用的方法,因此折扣:

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"
}
add_action('woocommerce_cart_calculate_fees'、'cart_price_progressive_折扣');
功能车\价格\累进\折扣(){
if(定义了('DOING'uajax'))
返回;
$has\u折扣=假;
$stotal\U ext=WC()->购物车->小计税;
//基于购物车金额条件的折扣百分比
如果($stotal_ext>=100&$stotal_ext<250){
$percent=-0.02;
$percent_text='2%';
$has\u折扣=真;
}elseif($stotal_ext>=250){
$percent=-0.04;
$percent_text='4%';
$has\u折扣=真;
} 
//算计
$折扣=$stotal_ext*$百分比;
//显示文本
$discount_text=__('discount','woocommerce')。$percent_text;
如果($有折扣){
WC()->购物车->添加费用($折扣\文本,$折扣,假);
}
//如果“true”,则“添加费用方法”中的最后一个参数启用计算税
}
这会出现在活动子主题(或主题)的function.php文件或任何插件文件中

此代码经过测试并正常工作。


类似的:


参考资料:

哇,这真的很有帮助。谢谢!有什么方法可以在购物车中显示折扣吗?折扣只出现在我的结账页面上,在购物车中显示的价格是没有折扣的完整价格。