【问题标题】:Apply a discount for a specific user role in Woocommerce为 Woocommerce 中的特定用户角色应用折扣
【发布时间】:2019-07-20 05:03:21
【问题描述】:

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

我发现 "Percentage discount based on user role and payment method in Woocommerce" 的答案非常符合我的需要,但不知道如何修改代码以满足我的需要,因为它还包含一个基于付款方式并仅在结帐时显示折扣,但我也需要将其显示在购物车中。

【问题讨论】:

    标签: php woocommerce cart user-roles discount


    【解决方案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 );
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 2021-02-28
      • 2021-01-06
      • 1970-01-01
      • 2020-02-07
      • 2018-12-23
      • 2020-10-18
      • 2021-01-29
      相关资源
      最近更新 更多