Replies: 0
I have a change_flat_rates_cost() function, but it works only when loading the page. but it is necessary for me that function worked at each change of the field “city”, (in checkout fields). I have tried to use ajax function and to call there add_filter() function, but it doesn’t help. I do it to change delivery cost without reset of the page depending on the chosen city
change_flat_rates_cost function (changes the shipping price)
function change_flat_rates_cost($rates, $package) {
$userid = get_current_user_id();
$meta_city = get_user_meta( $userid, 'billing_city', true );
if ( isset( $rates['shipping_method_1'] ) ) {
if ($meta_city == 'City1'){
$rates['shipping_method_1']->cost = 100;
}
if ($meta_city == 'City2'){
$rates['shipping_method_1']->cost = 200;
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'change_flat_rates_cost', 10, 2 );
ajax function:
add_action( 'wp_ajax_change_shipping', 'change_shipping' );
add_action( 'wp_ajax_nopriv_change_shipping', 'change_shipping' );
function change_shipping() {
global $woocommerce;
add_filter( 'woocommerce_package_rates', 'change_flat_rates_cost', 10, 2 );
die();
}