我在woocommerce中添加了一个自定义字段,其中包含图片帧的额外价格,现在如果图片价格为10美元,用户选择了一个帧,则加起来为5美元,总价格为15美元。
现在如果我添加另一个产品,它的选择自定义框架价格应该被添加。例如产品1价格为:10美元,其上选择的框架为:frame1,其价格为5美元,因此该产品的总价格为15美元,如果产品2加上价格10美元,并选择frame2,其价格为6美元,该产品的总价格为16美元,但grandtotal将为31美元
add_filter( 'woocommerce_get_discounted_price', 'calculate_discounted_price', 10, 2 );
// Display the line total price
add_filter( 'woocommerce_cart_item_subtotal', 'display_discounted_price', 10, 2 );
function calculate_discounted_price( $price, $values )
{
$price += $_SESSION['framed_price'];
return $price;
}
}
我在会话中存储帧值,每次用户点击帧时,它都会更新,我使用ajax,直到一切正常工作。我也得到了值。
这个函数基本上是在添加的产品上迭代,并将最后一帧的价格添加到购物车中的每个产品。
我们如何将产品价格加上它的定制框架价格?
我找到了一个答案,那就是解决这个问题:
// Change the line total price
add_filter( 'woocommerce_get_discounted_price', 'calculate_discounted_price', 10, 2 );
// Display the line total price
add_filter( 'woocommerce_cart_item_subtotal', 'display_discounted_price', 10, 2 );
function calculate_discounted_price( $price, $values ) {
// You have all your data on $values;
$price += 10;
return $price;
}
// wc_price => format the price with your own currency
function display_discounted_price( $values, $item ) {
return wc_price( $item[ 'line_total' ] );
}
参考:woocommerce,我如何在购物车产品总价中添加额外的成本?