I am trying to update the shipping prices for my shipping methods dynamically. I get the shipping costs from an API and I want to update the prices when the I successfully get the prices from the API response. I am using the following code :
function handle_api_response( $rates ) {
// api call code here.....
if ($response_code === 200){
$response_data = json_decode($response, true);
$price = $response_data['shipments']
}
add_filter( 'woocommerce_package_rates', 'set_shipping_prices', PHP_INT_MAX, 1 );
function set_shipping_prices( $rates ) {
foreach ( $rates as $rate_id => $rate ) {
$rates[ $rate_id ]->cost = $price;
}
return $rates;
}
}
The above code does not work but if I take the filter outside of the handle_api_response
function and set some static value to the cost it seems to work. Like this:
function handle_api_response( $rates ) {
// api call code here.....
if ($response_code === 200){
$response_data = json_decode($response, true);
$price = $response_data['shipments']
}
}
add_filter( 'woocommerce_package_rates', 'set_shipping_prices', PHP_INT_MAX, 1 );
function set_shipping_prices( $rates ) {
foreach ( $rates as $rate_id => $rate ) {
$rates[ $rate_id ]->cost = 50;
}
return $rates;
}
My problem is that, since I get the price value from the API I need to pass the price from the API response to set_shipping_prices
which runs when the filter is triggered.