I recently tried to modify all my shipping rates with hook to apply discount.
Here's my code :
add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates' );
function woocommerce_package_rates( $rates ) {
$user_id = get_current_user_id();
if ( ! wc_memberships_is_user_active_member( $user_id, 'silver' ) ) { return $rates; }
$discount_amount = 30; // 30%
foreach($rates as $key => $rate ) {
$rates[$key]->cost = $rates[$key]->cost - ( $rates[$key]->cost * ( $discount_amount/100 ) );
}
return $rates;
}
But one more step is the tax ! I got wrong tax.
For example I have my shipping rate who cost 3$
. With the discount, it's now 2,10$
.
I buy one item for 2$
and the shipping 2.10$
.
I got 1$ for the tax (as the 3$ shipping cost. look like he doesn't take the changes) and normally it's 0.82$
.
What do I need to get the correct tax calculation?
Updated: add tax cost calculation, and removed some typos.
There is some little errors on your code and you have missed the tax calculation discount. I have revisited your code a bit, you should try this:
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.