woocommerce add custom price while add to cart

2.5k views Asked by At

Hi I need to add an extra price to product price while add to cart. http://url/warenkorb/?add-to-cart=1539&added_price=5.00

I have used the code following code to achive this.

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

It shows the modified price on add to cart page but not in the cart/checkout page. Please Help me to achieve this. Thanks in advance.

1

There are 1 answers

0
Sark On

You have to use woocommerce_before_calculate_totals hook for this purpose, like this

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