在WooCommerce中,我正在尝试计算购物车中可变产品的价格。我想将产品价格乘以一些自定义购物车项目数值。
这是我的代码:
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;
}
}
价格计算不起作用。我做错了什么?
此钩子中的$price
参数是格式化的产品项目价格,然后您需要原始价格才能使其适用于您的自定义计算。请尝试以下方法:
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;
}
它应该工作。