Apply a discount for a specific user role in Woocommerce

不想你离开。 提交于 2019-12-02 09:04:57

问题


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'.

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.


回答1:


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 );
}

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



来源:https://stackoverflow.com/questions/54889136/apply-a-discount-for-a-specific-user-role-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!