动态更改产品价格woocommerce [英] Change product price dynamically woocommerce
本文介绍了动态更改产品价格woocommerce的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向woocommerce中的产品价格动态添加自定义费用.我过去已经做过很多次,但是现在无法正常工作.这是我的代码.
I am trying to add custom fee to product price in woocommerce dynamically. I have done this many times in past, but its not working right now. Here is my code.
function calculate_eyehole_fee( $cart_object ) {
global $isProcessed;
if( !WC()->session->__isset( "reload_checkout" )) {
$eyeHoleFee = 30.00;
$ribbonFee = 20.00;
// Get exchange rate details and defined fees
$strCurrencyCode = get_woocommerce_currency();
$arrExchangeRates = get_option('wc_aelia_currency_switcher');
$fltExchangeRate = $arrExchangeRates['exchange_rates'][$strCurrencyCode]['rate'];
$eveHoleCurrFee = $eyeHoleFee * $fltExchangeRate;
$ribbonCurrFee = $ribbonFee * $fltExchangeRate;
foreach ( $cart_object->cart_contents as $key => $value ) {
$additionCost = 0.0;
if( isset( $value["eyeHoleReq"] ) && $value["eyeHoleReq"] == 'yes' ) {
$fltEyeFee = $eveHoleCurrFee;
$additionCost = $fltEyeFee;
}
if( isset( $value["eyeRibbon"] ) && $value["eyeRibbon"] == 'yes' ) {
$fltRibbonFee = $ribbonCurrFee;
$additionCost += $fltRibbonFee;
}
$cart_object->cart_contents[$key]['data']->price += $additionCost;
}
$isProcessed = true;
}
print('<pre>');print_r($cart_object);print('</pre>');
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_eyehole_fee', 99 );
我的价格在购物车对象中已更新,但没有反映任何位置.因此,总数也会被错误地计算.
My price is updated in cart object, but it reflects no where. Hence totals are also miscalculated.
推荐答案
在woocommerce 3.0更新之后,我们无法直接设置价格.相反,我们必须使用set_price()方法.因此,以下方法应该起作用:
After woocommerce 3.0 update we cant set price directly. Instead we have to use set_price() method. So following should work:
function calculate_eyehole_fee( $cart_object ) {
global $isProcessed;
if( !WC()->session->__isset( "reload_checkout" )) {
$eyeHoleFee = 30.00;
$ribbonFee = 20.00;
// Get exchange rate details and defined fees
$strCurrencyCode = get_woocommerce_currency();
$arrExchangeRates = get_option('wc_aelia_currency_switcher');
$fltExchangeRate = $arrExchangeRates['exchange_rates'][$strCurrencyCode]['rate'];
$eveHoleCurrFee = $eyeHoleFee * $fltExchangeRate;
$ribbonCurrFee = $ribbonFee * $fltExchangeRate;
foreach ( $cart_object->get_cart() as $key => $value ) {
$additionCost = 0.0;
if( isset( $value["eyeHoleReq"] ) && $value["eyeHoleReq"] == 'yes' ) {
$fltEyeFee = $eveHoleCurrFee;
$additionCost = $fltEyeFee;
}
if( isset( $value["eyeRibbon"] ) && $value["eyeRibbon"] == 'yes' ) {
$fltRibbonFee = $ribbonCurrFee;
$additionCost += $fltRibbonFee;
}
$defPrice = $value['data']->get_price('edit');
$value['data']->set_price((float) $defPrice + $additionCost);
}
$isProcessed = true;
}
print('<pre>');print_r($cart_object);print('</pre>');
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_eyehole_fee', 99 );
这篇关于动态更改产品价格woocommerce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文