woocommerce在添加到购物车时添加自定义价格

时间:2015-06-09 13:19:26

标签: woocommerce

您好,我需要在添加到购物车时为产品价格添加额外价格。 http://url/warenkorb/?add-to-cart=1539&added_price=5.00

我使用了以下代码来实现此目的。

add_filter( 'woocommerce_add_cart_item', 'c_other_options_add_cart_item', 20, 1 );
function c_other_options_add_cart_item( $cart_item ) {

    if (isset($cart_item['_other_options'])) :
        if( isset($cart_item['_other_options']['product-price']) )
            $extra_cost = floatval($cart_item['_other_options']['product-price']);

        $cart_item['data']->adjust_price( $extra_cost );
        // here the real adjustment is going on...

    endif;

    return $cart_item;

}

add_filter( 'woocommerce_add_cart_item_data', c_other_options_add_cart_item_data', 10, 2 );

function c_other_options_add_cart_item_data($cart_item_meta, $product_id){

    global $woocommerce;

    $product = new WC_Product( $product_id);
    $price = $product->price;

    if(empty($cart_item_meta['_other_options']))
        $cart_item_meta['_other_options'] = array();

    $cart_item_meta['_other_options']['product-price'] = esc_attr($_REQUEST['price']) - $price;

    return $cart_item_meta;
}

它显示添加到购物车页面的修改价格,但不显示在购物车/结帐页面中。请帮助我实现这一目标。提前谢谢。

1 个答案:

答案 0 :(得分:1)

为此必须使用woocommerce_before_calculate_totals钩子, 像这样

function calculate_extra_fee( $cart_object ) {
    /* Extra fee */
    $additionalPrice = 100;
    foreach ( $cart_object->cart_contents as $key => $value ) {       
        /* if you want to add extra fee for particular product, otherwise remove the if condition */
        if( $value['product_id'] == 100) {
            $quantity = intval( $value['quantity'] );
            $orgPrice = intval( $value['data']->price );
            $value['data']->price = ( ( $orgPrice + $additionalPrice ) * $quantity );
        }           
    }
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_extra_fee', 1, 1 );