简体   繁体   中英

Changing cart product price in Woocommerce

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?

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.

I don't know if I'm in the right topic. But I have a question with Woocomerce

How do I get the value of the product and divide it into installments.

Is this possible via HTML or PHP?

Example.

A product that costs $120.00

I would like to show my client that he can buy in up to 6 interest-free installments.

I would like woocommerce to have a plugin with this function, via shortcode.

On the product page or product gallery, I could report:

Product value = X

or 6 installments of X/6.

Could someone help me with a code like this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM