为 Woocommerce 中的特定用户角色应用折扣

时间:2023-03-19
本文介绍了为 Woocommerce 中的特定用户角色应用折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a woocommerce store, with 3 user roles, I want to provide a 10% discount on the cart total only for a user role 'company'.

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

I found "Percentage discount based on user role and payment method in Woocommerce" answer that is very neer of what I need, but don't know how to modify the code to feet my needs, as it contains also a condition based on payment method and displaying the discount only at checkout, but I need it to display in cart as well.

推荐答案

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

The following code will apply a 10% discount for 'company' user role (on cart and checkout):

// 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 文件中.它应该有效.

Code goes on functions.php file of your active child theme (or active theme). It should works.

这篇关于为 Woocommerce 中的特定用户角色应用折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:根据 Woocommerce 中选择的付款方式禁用运输方式 下一篇:在 WooCommerce 单个产品和购物车页面中输出自定义

相关文章

最新文章