1
votes

In WooCommerce, I'm trying to calculate the price of a variable product in the cart. I want to multiply the product price with some custom cart item numerical value.

Here is my code:

add_filter( 'woocommerce_cart_item_price', 'func_change_product_price_cart', 10, 3 );
function func_change_product_price_cart($price, $cart_item, $cart_item_key){
    if (isset($cart_item['length'])){
        $price = $cart_item['length']*(price of variation);
        return $price;
    }

}

The price calculation doesn't work. What I am doing wrong ?

1
Why are you overwriting $price ?B001ᛦ
Ah! I can just do this? $new_price = $price*$cart_item['length']; return $new_price.Paudun
yes...exactly!!B001ᛦ
Or even just return $price*$cart_item['length']; without the extra variable.Dave
Or even just return... This is more elegant of course @DaveB001ᛦ

1 Answers

3
votes

The $price argument in this hook is the formatted product item price, then you need the raw price instead to make it work on your custom calculation. Try the following instead:

add_filter( 'woocommerce_cart_item_price', 'change_cart_item_price', 10, 3 );
function change_cart_item_price( $price, $cart_item, $cart_item_key ){
    if ( WC()->cart->display_prices_including_tax() ) {
        $product_price = wc_get_price_including_tax( $cart_item['data'] );
    } else {
        $product_price = wc_get_price_excluding_tax( $cart_item['data'] );
    }

    if ( isset($cart_item['length']) ) {
        $price = wc_price( $product_price * $cart_item['length'] );
    }
    return $price;
}

It should work.