Once a client of mine, running a WooCommerce store, wanted to change a product price if the customer adds another product in the WooCommerce cart. The idea was to offer reduced price of a product if the customer buys specific product.

We know that every product in WooCommerce has a regular price and a Sale price. Those are edited in WooCommerce admin. Now we will change the product price programmatically.

For this to work, we have to run two functions. One is to check if the first product is in cart and the second is to change the price of the second product. It doesn’t matter if the product price we’re changing is simple or variable or any other.

PHP snippet: change product price in cart in WooCommerce

// Lets check if product is in cart

function webroom_product_in_cart($product_id){

	$product_cart_id = WC()->cart->generate_cart_id( $product_id );
    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
 
    if ( $in_cart ) {
        return true;
    }
	return false;
}

// Lets change the product price in cart

add_action( 'woocommerce_before_calculate_totals', 'webroom_change_price_of_product' );

function webroom_change_price_of_product( $cart_object ) {	
    $target_product_id = 106020; // CHANGE THIS WITH YOUR PRODUCT ID original price: 149 EUR
	if(webroom_product_in_cart(223344)) {
	// Product is already in cart
		foreach ( $cart_object->get_cart() as $key => $value ) {
			if ( $value['product_id'] == $target_product_id ) {
				$value['data']->set_price(119.20); // CHANGE THIS: set the new price
				$new_price = $value['data']->get_price();
			}
		}
	}
}

Next steps: copy and paste the above snippet in your child theme’s functions.php file. Remember to change 3 paraments:

  1. $target_product_id – add the product id which price you want to change
  2. webroom_product_in_cart(223344) – change this with the product id you want to check if is in the cart
  3. $value[‘data’]->set_price(119.20) – change this with the new desired price of the product in 1.

How to get Product id in WooCommerce

The easiest way to get the product id in WooCommerce is to edit a product and look at the url:

https://www.example.com/wp-admin/post.php?post=1493&action=edit

You will find the product id in ?post=1493.

To change the product price we are using woocommerce_before_calculate_totals hook. Learn more about it here.

Share:

Leave a Reply