I'm writing a custom WordPress function that will change the flat_rate shipping when a customer changes the "State" field from a select menu. Currently I'm doing it in my theme's functions.php
I have created a custom field to represent "State" field as a drop down menu in the billing fields. I used "WooCommerce Checkout Manager" plugin to setup the custom field and disabled the default "State" field.
Now I want to change the shipping cost depending on the value of my custom "State" field. I'm unable to retrieve the data of the field. Also I want to know what hook I can use to change the flat rate shipping once this field's value is changed.
I've used this filter hook (woocommerce_package_rates) and it doesn't work.
Here is my code to do it which I got it from another tutorial then made my customization
function wc_ninja_change_flat_rates_cost( $rates, $package ) {
$destination = $package['destination'];
$city = $destination['myfield12']; // getting the city field value
// Make sure flat rate is available
if ( isset( $rates['flat_rate'] ) ) {
if ( $city == 'Alex' || $city == 'الإسكندرية' ) {
// Set flat rate to cost $10 more
$rates['flat_rate']->cost = 30;
}
else {
$rates['flat_rate']->cost = 20;
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2 );