Total : 0.00 €

How to check WooCommerce add to cart price

If you want to check the WooCommerce product price before your customer adds a product to the cart, you cannot use the "woocommerce_add_to_cart_validation" function. But the following is a really smart trick about how to do that:

This piece of code checks if the price is 0, in this case, an error message will be shown and the product will be removed from the cart, so the customer cannot buy it.

Checking add to cart price

To make this piece of code work, you need to append it to your "functions.php" file, located in your "/wp-content/themes/YOUR_THEME/ path":

/* Price must be different from 0 to be added to the cart */
function filter_custom_wpc_add_to_cart_callback($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data){
	global $woocommerce;
	
	foreach(WC()->cart->get_cart() as $cart_item_key => $values){
		$cartItemPrice		= $values['data']->get_price();
		
		if($cartItemPrice == 0){
        
        	/* Showing the error message */
			wc_add_notice("Sorry but it's not possible to add this product to cart", "error");
            
            /* Removing the product from the cart */
			$woocommerce->cart->remove_cart_item($cart_item_key);
			
			return;
		}
	}
	
}
add_action('woocommerce_add_to_cart', 'filter_custom_wpc_add_to_cart_callback', 20, 6);

 

Of course, you can change the error message to be more appropriate.

 

Cart

Total : 0.00 €