Sometimes, we want to recalculate the price of a specific product, which we have already added to the cart.
So, here we will use woocommerce_before_calculate_totals hook to recalculate the price before set the totals of cart.
If you want to change the price of a specific product in the cart depending on the condition then I’ll show you an easy method to do this. You can use
woocommerce_before_calculate_totals hook. You can learn more about action hook here.
This hook will run before calculating the total of all cart item prices. And will do modification the final total with our custom price of the specific product.
Set custom price for all products:
Look at the example:
The above example is to set the custom price for all products.
Set custom price for specific products:
Next, we will learn how we can set the custom price of specific products and also with specific conditions.
When customers will add the product of a specific category (ID: 926) in the cart with a certain amount (e.g 5), so this product category will receive a 45% discount but it will not affect the price of other categories of products.
Look at this example:
Explanation: In the above example, first, we count the quantity of a specific product category in the cart item, and then we checked that the quantity is greater than 5 to give a 45% discount on that specific category’s product.
So, If the quantity will be more than 5 then applied the discount of 45% in the cart for those products.