0
votes

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:

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?

1

1 Answers

0
votes

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.