In this tutorial I will show you how we can override prices of the products that are already in the Cart with the help of woocommerce_before_calculate_totals action hook and cart object.Here we are going to deal with products that have already been added to cart, if you would like to add products to the cart with a custom price, I can recommend you this example.
Below we are going to set the same price ($10) for every product in the cart programmatically.
add_action( 'woocommerce_before_calculate_totals', 'wpdev_recalc_price' );
function wpdev_recalc_price( $cart_object ) {
foreach ( $cart_object->get_cart() as $hash => $value ) {
$value[ 'data' ]->set_price( 10 );
}
}
Example. Change Product Price Based on Quantity
Now it is time to do something a little bit more interesting. The idea is when a customer adds a certain quantity of a specific product from a specific category (ID 25) to the cart, these products will get 50% off. But it should never affect a Wizard hat product (ID 12345).
Cart totals are going to be updated too.
/**
* Change Product Prices Programmatically Based on Quantity
*
*/
add_action( 'woocommerce_before_calculate_totals', 'wpdev_recalculate_price' );
function wpdev_recalculate_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$product_category_id = 25;
$product_id_to_exclude = 12345;
// it is our quantity of products in specific product category
$quantity = 0;
// you can always print_r() your object and look what's inside
// print_r( $cart_object ); exit;
// $hash = cart item unique hash
// $value = cart item data
foreach ( $cart_object->get_cart() as $hash => $value ) {
// check if the product is in a specific category and check if its ID isn't 12345
if( in_array( $product_category_id, $value[ 'data' ]->get_category_ids() ) && $value[ 'product_id' ] !== $product_id_to_exclude ) {
// if yes, count its quantity
$quantity += $value[ 'quantity' ];
}
}
// change prices
if( 3 < $quantity ) {
foreach ( $cart_object->get_cart() as $hash => $value ) {
// I want to make discounts only for products in category with ID 25
// and I never want to make discount for the product with ID 12345
if( in_array( $product_category_id, $value[ 'data' ]->get_category_ids() ) && $value[ 'product_id' ] !== $product_id_to_exclude ) {
$newprice = $value[ 'data' ]->get_price() / 2;
$value[ 'data' ]->set_price( $newprice );
}
}
}
}
If you’re wondering where I’ve found all those methods like set_price(), get_category_ids(), look at the WC_Product object, you can find it in WooCommerce plugin directory in /includes/abstracts/abstract-wc-product.php or in the documentation. And by the way, variations don’t have categories.
If you read my blog and still don’t know where to insert this type of code, it is sad. Try your current theme functions.php then.