问题
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.
回答1:
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 );
来源:https://stackoverflow.com/questions/44096695/change-product-price-dynamically-woocommerce