0

I'm trying to build a site where the price of a product varies based on details entered by the customer. Originally I was just using the woocommerce_get_price hook to modify the price which seemed to work fine.

I've now been asked to allow the customer to enter details, put the item in their basket, then go through the process again, meaning they could have multiple copies of the same item in the basket with different prices.

woocommerce_get_price wouldn't work here as when this hook runs I don't know if it's a cart item being loaded, or if it is, I don't have access to the cart item data to look for a unique price. I tried every hook I could find to modify pricing in the basket**, most of which seemed to either only change the display price and not totals, or do nothing at all. I finally ended up with the following:

add_filter('woocommerce_cart_loaded_from_session', [$this, 'setBasketPricing'], 20, 1);

public function setBasketPricing($cart){

    foreach($cart->get_cart() as $key => $item){

        if( is_array($item['XXX']) && $item['XXX']['price'] )
            $item['data']->set_price($item['XXX']['price']);
    }
}

The price is stored in the cart item data when added to the basket. After the basket is loaded I update the price of the item, all done just after the basket is loaded.

This seems to work well enough to show the correct prices in the cart, totals, payment and back-end order details. However, the receipt page and emails show the original product price.

Are they hooks that will let me alter the cart item prices displayed in these additional locations, or ideally a better hook to override the price of an item in the basket that changes it everywhere?

**Is there any decent documentation for hooks anywhere, other than the gigantic list on docs.woocommerce.com which involves scouring through the entire list then reverse engineering what the arguments are from the source code? Looking at hookr.io is always fun seeing "The Array" & "The Int" as a description for hook arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.