Home Changing cart product price in Woocommerce
Reply: 0

Changing cart product price in Woocommerce

user1455
1#
user1455 Published in June 19, 2018, 4:12 pm

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;
        endif;
    endforeach;
}
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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO