Dynamic way to update shipping method price in WooCommerce
P粉605233764
2023-08-13 18:08:43
<p>I'm trying to dynamically update shipping prices for my shipping methods. I get the shipping price from the api and want to update the price when I successfully get the price from the api response. I'm using the following code: </p>
<pre class="brush:php;toolbar:false;">function handle_api_response( $rates ) {
//The api calling code is 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;
}
}</pre>
<p>The above code doesn't work, but if I move the filter out of the handle_api_response function and set some static value to the fee, it seems to work. Like this: </p>
<pre class="brush:php;toolbar:false;">function handle_api_response( $rates ) {
//The api calling code is 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;
}</pre>
<p>My problem is that since I'm getting the price value from the api, I need to pass the price from the api response to the set_shipping_prices function that runs when the filter is triggered. </p>
This code is untested and may need some tweaking, but it can be the correct path to make your external API calls work.
We can try to use the WC_Session variable to set the shipping fee we want to pass:
Then we can call the WC_Session variable in your hook function:
However, we need something else to refresh the cached shipping method in order for it to take effect:
Finally, we unset the WC Session variable (on checkout first load and thank you page) :
Put the code into your child theme's functions.php file (or into a plugin). It may work.
Related: Remove shipping costs after checking custom checkbox in WooCommerce checkout