提问者:小点点

在WooCommerce中为特定用户角色申请折扣


我有一个woocommerce商店,有3个用户角色,我想只为一个用户角色“公司”提供购物车总额的10%折扣。

我发现“Woocommerce中基于用户角色和付款方式的百分比折扣”答案与我的需求不符,但我不知道如何修改代码以满足我的需求,因为它还包含一个基于付款方式的条件,仅在结帐时显示折扣,但我也需要在购物车中显示折扣。


共1个答案

匿名用户

以下代码将对“公司”用户角色(购物车和结帐)应用10%的折扣:

// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_on_user_role( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    // Only for 'company' user role
    if ( ! current_user_can('company') )
        return; // Exit

    // HERE define the percentage discount
    $percentage = 10;

    $discount = $cart->get_subtotal() * $percentage / 100; // Calculation

    // Applying discount
    $cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}

代码继续执行功能。php活动子主题(或活动主题)的文件。它应该有效。