How to change price based on Quantity added on cart page without a plugin?

If the client wants to vary price based on a number of quantity added to cart for specific products, then as a developer we must ignore the use of the plugin. We must do necessary changes as per hooks and filters of the WooCommerce.

Rather than using a plugin, try to use the code snippet which will help in site speed and code security.

To apply such logic in WooCommerce is possible using hooks and the hook related to this snippet is “woocommerce_before_calculate_totals”

Let’s take an example:
The default price of the product is 50 USD
The client want vary the price of the product if there are 50 quantity for the same product. i.e client wants to add a discount for the product if the quantity is 50.

add_action( 'woocommerce_before_calculate_totals', 'geeker_quantity_based_product_price_callback', 9999 );
 
function geeker_quantity_based_product_price_callback( $cart ) {
 
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
 
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
 
    // Define discount rules and thresholds
    $quantiyincart1 = 101; // Change price if items > 100
    $discount1 = 50; // Reduce unit price by 50%
    
    $quantiyincart2 = 1001; // Change price if items > 1000
    $discount2 = 0.1; // Reduce unit price by 10%
 
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      $product_id = $cart_item['product_id'];
      if ( $cart_item['quantity'] >= $quantiyincart1 && $cart_item['quantity'] < $quantiyincart2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount1 ), 2 );
         $cart_item['data']->set_price( $price );
      } elseif ( $cart_item['quantity'] >= $quantiyincart2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
         $cart_item['data']->set_price( $price );
      }    
    }
    
 }

Leave a Comment

Your email address will not be published. Required fields are marked *