Paudun
Paudun

Reputation: 287

Display a custom calculated cart item price in WooCommerce

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 ?

Upvotes: 1

Views: 2338

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

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.

Upvotes: 3

Related Questions