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

2024-02-14

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

I found "基于 Woocommerce 中的用户角色和付款方式的百分比折扣 https://stackoverflow.com/questions/51352055/percentage-discount-based-on-user-role-and-payment-method-in-woocommerce/51352908#51352908"答案与我需要的非常接近,但不知道如何修改代码以满足我的需求,因为它还包含基于付款方式的条件并仅在结帐时显示折扣,但我需要它显示购物车也是如此。


以下代码将为“公司​​”用户角色应用 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您的活动子主题(或活动主题)的文件。它应该有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 Woocommerce 中的特定用户角色应用折扣 的相关文章

随机推荐