Search code examples
wordpresswoocommerceproductcart

Apply discount based on user role when they buy x quantity of specific product category in WooCommerce


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?


Solution

  • 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;
        $current_total = 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'] ) ) {
                // Get quantity
                $product_quantity = $cart_item['quantity'];
    
                // Add to quantity total
                $current_quantity += $product_quantity;
                
                // Get price
                $product_price = $cart_item['data']->get_price();
                
                // Add to current total
                $current_total += $product_price * $product_quantity;
            }
        }
    
        // Greater than or equal to
        if ( $current_quantity >= $minimun_quantity ) {
            // Calculation
            $discount = $current_total * $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 );