问题
After the update my custom shipping amount rules are not working. Before the update I was using the following code to update shipping amount.
add_action('woocommerce_calculate_totals', 'mysite_box_discount');
function mysite_box_discount($cart )
{
$cart->shipping_total=100;
return $cart;
}
After the update the structure of $cart array has changed and the above code has stopped working. Now the data coming in form of a protected array. I found that $cart->get_shipping_total(); can fetch me shipping amount.
I also found following function to update shipping amount.
$cart->set_shipping_total($amount);
So I used it in the following way, but its not working.
add_action('woocommerce_calculate_totals', 'mysite_box_discount');
function mysite_box_discount($cart )
{
$cart->set_shipping_total(100);
return $cart;
}
Can anyone help me and tell how can I use this function or if there is some other way to do it. Thank you.
回答1:
You can use instead woocommerce_package_rates
filter hook to set the cost of your shipping methods, which will be similar to your old code:
add_filter('woocommerce_package_rates', 'custom_shipping_costs', 10, 2 );
function custom_shipping_costs( $rates, $package ){
// Loop through shipping methods rates
foreach ( $rates as $rate_key => $rate ){
// Targeting all shipping methods except "Free shipping"
if ( 'free_shipping' !== $rate->method_id ) {
$has_taxes = false;
$taxes = [];
$rates[$rate_key]->cost = 100; // Set to 100
// Taxes rate cost (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){
$has_taxes = true;
$taxes[$key] = 0; // Set to 0 (zero)
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
You might need to refresh shipping cached data: disable, save and enable, save related shipping methods for the current shipping zone, in Woocommerce shipping settings.
In this hook if you need to loop through cart items (to make some calculations for example), you will use inside the function code:
foreach( $package['contents'] as $cart_item_key => $cart_item ) {
$product = $cart_item['data']; // Get the WC_Product instance Object
// your code
}
来源:https://stackoverflow.com/questions/53538372/set-cart-shipping-total-amount-issue-after-woocommerce-update