Home Changing cart product price in Woocommerce
Reply: 1

Changing cart product price in Woocommerce

Chan Hui Kent
Chan Hui Kent Published in 2016-11-23 02:45:32Z

I wanted to implement a buy 3 free 1 feature, so I wrote a script that detect whether customer has 3 same items in cart and automatically add 1 more same item to the cart. Then using another hook, I overwrite the price of the product to 0.

I googled the solution and used the same approach found on:

  • WooCommerce: Add product to cart with price override?
  • woocommerce add custom price while add to cart

Here is the code sample:

function setGiftPriceToZero($cart_object){
    foreach($cart_object->cart_contents as $k=>$item):
        if(isset($item['variation']['promo']) && ($item['variation']['promo']) == 'buy 3 free 1'):
            $item['data']->price = 0;
add_action('woocommerce_before_calculate_totals', 'setGiftPriceToZero');

When Woocommerce calculate the subtotal for the cart, it always add in the original price of the product that is supposed to be free. For example, when I added 3 $100 item to cart, the cart subtotal ends up with $400 instead of $300.

I digged deeper into the Woocommerce code and found that in https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#1139, $item['data']->get_price() is used which always return the original price for the item.

Is there anyway to fix this using hooks/apis instead of editing Woocommerce core file?

Chan Hui Kent
Chan Hui Kent Reply to 2016-11-23 08:08:12Z

I have found the culprit of this error. It's caused by conflict from another plugin called Woocommerce Role Based Price. This plugin overwrite the cart item price at the end of the cart total calculation flow. This is why get_price() function always return the specified price for the item.

Now I only have to edit the plugin file so that it plays nicely with my logic.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305164 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO