add_action('wp_ajax_set_shipping_price', 'set_shipping_price');
add_action('wp_ajax_nopriv_set_shipping_price', 'set_shipping_price');
function set_shipping_price(){
if (isset($_POST['cost'])){
$new_cost = $_POST['cost'];
}
WC()->session->set( 'shipping_calculated_cost', $new_cost );
wp_die();
}
add_filter('woocommerce_package_rates', 'update_shipping_costs_based_on_cart_session_custom_data', 10, 2);
function update_shipping_costs_based_on_cart_session_custom_data( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$cost = '0';
$calculated_cost = WC()->session->get( 'shipping_calculated_cost');
foreach ( $rates as $rate_key => $rate ) {
$method_id = $rate->method_id;
$rate_id = $rate->id;
if ( 'flat_rate' === $method_id ) {
if( ! empty( $calculated_cost ) ) {
$cost = $calculated_cost;
}
$rates[$rate_id]->cost = $calculated_cost;
}
}
return $rates;
}