WooCommerce Set Custom Product Price When Adding To Cart – In this post, we’ll see how we can override the price of product when adding the product into cart.
Price overriding in cart is useful feature if we want to increase or decrease product price by any static value. This can be done by creating price rules also instead of static price value. This is very useful code snippet from developer point of view.
We’ll understand the code by taking an example with static price value. We’ll use action hook ‘woocommerce_before_calculate_totals’ to achieve our goal.
Let’s start with an example plugin –
<?php /** * Plugin Name: Webkul Override Product Price on Add to Cart * Description: Add product to cart with override price * Author: Webkul * Author URI: https://webkul.com * Plugin URI: https://webkul.com */ if ( ! class_exists( 'WK_Price_Override' ) ) { /** * */ class WK_Price_Override { function __construct() { add_action( 'woocommerce_before_calculate_totals', array( $this, 'wk_update_price' ) ); } function wk_update_price( $cart_object ) { $cart_items = $cart_object->cart_contents; if ( ! empty( $cart_items ) ) { $price = 100; foreach ( $cart_items as $key => $value ) { $value['data']->set_price( $price ); } } } } function wk_initialise_main_class() { new WK_Price_Override(); } add_action( 'plugins_loaded', 'wk_initialise_main_class' ); }
In above code snippet, we have initialised main class with ‘plugins_loaded’ action hook. As mentioned earlier, we have used hook ‘woocommerce_before_calculate_totals’ and in callback function, we retrieved cart items from cart object argument. And then we iterate through cart items and set price for each item. In this way we can override product price in cart.
Please check in below screenshots the difference between product price on product page and cart page.
As we can see product price is 18 USD. But from code we have override same to 100 USD. Check below the cart page –
Reference – http://hookr.io/actions/woocommerce_before_calculate_totals/
That’s all for custom label for product on shop and single page. Thanks for your time 🙂
Thank you very much is what I was looking for to solve a problem in the current project I am working on