Display a custom calculated cart item price in WooCommerce

前提是你 提交于 2020-03-24 00:37:10

问题


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:


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.



来源:https://stackoverflow.com/questions/55159369/display-a-custom-calculated-cart-item-price-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!