动态改变产品价格的woocommerce

时间:2017-05-21 12:12:02

标签: wordpress woocommerce hook-woocommerce

我正在尝试动态地在woocommerce中为产品价格添加自定义费用。我过去曾多次这样做过,但现在还不行。这是我的代码。

    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 );

我的价格在购物车对象中更新,但它没有反映在哪里。因此总计也算错了。

1 个答案:

答案 0 :(得分:0)

在woocommerce 3.0更新后,我们无法直接设定价格。相反,我们必须使用set_price()方法。以下应该有效:

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 );