I have this function and I need to get it working in woocommerce 3.* . It works perfectly in 2.6.*

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {

  global $woocommerce;

  $cart_item_meta['estimated_fare'] = WC()->session->get( 'estimated_fare' );


    $custom_price = $cart_item_meta['estimated_fare'] ; // This will be your custome price  
    $target_product_id = get_option('stern_taxi_fare_product_id_wc');
    foreach ( $cart_object->cart_contents as $key => $value ) {
        if ( $value['product_id'] == $target_product_id ) {
            $value['data']->price = $custom_price;
        }
    }
}

I’ve tried this :

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10 , 2);

function add_custom_price( $cart_obj ) {

  global $woocommerce;
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_item_meta['estimated_fare'] = WC()->session->get( 'estimated_fare' );


    $custom_price = $cart_item_meta['estimated_fare'] ; // This will be your custome price  
    $target_product_id = get_option('stern_taxi_fare_product_id_wc');
    foreach ( $cart_obj->get_cart as $key => $value ) {
        if ( $value['product_id'] == 20) { // $target_product_id ) {
            $value['data']->set_price = $custom_price;
        }

    }
}

but its still not working and i get 0.00 price in Cart.
Any ideas how to fix it?

Thnx in advance

Read more here: woocommerce_before_calculate_totals in woocommerce v3.*


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: