Set cart shipping total amount issue after Woocommerce update

无人久伴 提交于 2021-02-18 19:33:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!