I’m currently trying to apply a discount on shipping if a customer chooses a certain payment method.
For some reason, this applies the discount regardless of which payment method is chosen.
The code I’m using in functions.php
is:
function filter_woocommerce_package_rates( $rates, $package ) {
$min = 25;
$min2 = 25;
$max = 50;
$discount_percent = 50;
$payment_method = 'clearpay';
$chosen_payment_method = WC()->session->get('chosen_payment_method');
// Get cart total
$cart_total = WC()->cart->cart_contents_total;
// Condition
if ( $cart_total >= $min && $cart_total <= $max && $payment_method == $chosen_payment_method ) {
// (Multiple)
foreach ( $rates as $rate_key => $rate ) {
// Get rate cost
$cost = $rates[$rate_key]->cost;
// Set rate cost
$rates[$rate_key]->cost = $cost - ( ( $cost * $discount_percent ) / 100 );
}
wc_add_notice(
sprintf( 'Congratulations! Your shipping is now 50% off!' ,
wc_price( WC()->cart->total ),
wc_price( $minimum )
), 'success'
);
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
do_action( 'woocommerce_set_cart_cookies', true );
Any idea what’s wrong?
2
Answers
This is what I’m doing in order to get flat discount amounts for different payment methods
You can adapt it to your case
Your code contains unnecessary variables that you are either not using or using incorrectly. It is certainly not mentioned in your question description.
So to apply a shipping discount based on the chosen payment method you can use.
Note: Don’t forget to empty the cart, to refresh the WooCommerce shipping caches