I’m trying to set the shipping costs to 0 or change the shipping class to free shipping for specific products.
I’ve built a snippet which will be called correctly if the product is in cart via WC()->cart->get_cart()
.
The problem which I can’t figure out is how to set shipping to zero or change to free shipping.
This is working, but here my payment provider has a problem, because negative values for are not allowed:
$cart->add_fee( 'Versandkostenfrei', -$cart->get_shipping_total(), true, '' );`
The ‘unitPrice’ field cannot be negative, unless the ‘type’ is one of
the following: ‘discount’, ‘store_credit’, and ‘gift_card’.
But even if this is “fixed”, the shiping costs will be shown in checkout with a separate negative position to set the shipping to zero.
This is also not nice customer view.
So I tried with:
function set_shipping_costs_to_zero( $rates ) {
foreach ( $rates as $rate_id => $rate ) {
$rates[ $rate_id ]->cost = 0;
if ( isset( $rates[ $rate_id ]->taxes ) && is_array( $rates[ $rate_id ]->taxes ) ) {
foreach ( $rates[ $rate_id ]->taxes as $key => $value ) {
$rates[ $rate_id ]->taxes[ $key ] = 0;
}
}
}
return $rates;
}
Which doesn’t set the price to 0.
Or even with this simple unset:
unset( $rates[$rate_id] );
Used the function in the following hooks without success:
- woocommerce_before_calculate_totals,
- woocommerce_package_rates,
- woocommerce_cart_calculate_fees.
Any ideas?