Home > Mobile >  Apply discount based on user role when they buy x quantity of specific product category in WooCommer
Apply discount based on user role when they buy x quantity of specific product category in WooCommer

Time:11-02

I want to give discount for my customer based user role ex:

  • for user role (subscriber) 50% discount if they buy 25 products from a specific category.

If use a snippet but it is not cover the second part of my question (25 products from a specific category).

// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_on_user_role', 20, 1 );
function discount_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 = 50;

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

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

Any advice?

CodePudding user response:

For the category categorie-1 (adjust if desired) you can use a counter based on the product quantity in the cart.

When this is equal to 25 or more you can apply the discount.

So you get:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    // Only for 'company' user role
    if ( ! current_user_can( 'company' ) )
        return;
    
    // Category
    $category = 'categorie-1';

    // Percentage discount
    $percentage = 50; // 50%
    
    // Min quantity
    $minimun_quantity = 25;
    
    // Initialize
    $current_quantity = 0;

    // Loop though each cart item
    foreach ( $cart->get_cart() as $cart_item ) {
        // Has certain category     
        if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
            // Quantity
            $product_quantity = $cart_item['quantity'];

            // Add to total
            $current_quantity  = $product_quantity;
        }
    }

    // Greater than or equal to
    if ( $current_quantity >= $minimun_quantity ) {
        // Calculation
        $discount = $cart->get_subtotal() * $percentage / 100;

        // Applying discount
        $cart->add_fee( sprintf( __( 'Discount (%s)', 'woocommerce' ), $percentage . '%'), -$discount, true );     
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
  • Related