如果在Woocommerce中未应用优惠券,则自动为用户角色提供折扣

问题描述 投票:2回答:1

我在下面有此代码,但是我希望它仅在用户未使用其他代码且用户使用其他优惠券的情况下才有效,然后禁用此优惠券。

基于Apply a discount for a specific user role in Woocommerce的答案代码,我一直在尝试查看如何检查是否有优惠券,但无法弄清楚。

// 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('affiliate') )
        return; // Exit

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

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

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

感谢您的任何帮助。

php wordpress woocommerce cart discount
1个回答
0
投票

如果购物车中没有已应用的优惠券,请尝试以下操作将根据特定的用户角色设置自定义折扣:

// Applying conditionally a discount for a specific user role and no applied coupons
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 'affiliate' user role
    if ( ! current_user_can('affiliate') )
        return; // Exit

    // Only if there is no applied coupons in cart
    if ( ! empty( $cart->get_applied_coupons() ) )
        return; // Exit

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

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

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

代码在您的活动子主题(或活动主题)的functions.php文件上。经过测试,可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.