I like to give a discount on some Local Pickup shipping methods. With the code below, I get a discount on all shipping methods (including also Flat Rate and Free Shipping).
But I would like this discount to be applied only on some specific Local Pickup shipping methods I have defined here below in my code:
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_pickup_shipping_method', 10, 1 );
function custom_discount_for_pickup_shipping_method( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only on checkout page
if ( is_checkout() ) {
$percentage = 5; // <=== Discount percentage
$chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
$chosen_shipping_method = explode(':', $chosen_shipping_method_id)[0];
// Only for Local pickup chosen shipping method
if ( strpos( $chosen_shipping_method_id, 'local_pickup:63', 'local_pickup:64', 'local_pickup:65', 'local_pickup:66', 'local_pickup:67', 'local_pickup:68', 'local_pickup:69' ) !== false ) {
// Calculate the discount
$discount = $cart->get_subtotal() * $percentage / 100;
// Add the discount
$cart->add_fee( __('3% afhaalkorting, levering vanuit ons magazijn') . ' (' . $percentage . '%)', -$discount );
}
}
}
First in WooCommerce you can have multiple shipping methods applied on a split cart, so an array of shipping methods.
Here you are trying to apply a discount from some Local Pickup shipping methods, so from an other array of defined shipping methods.
In this case is better to use the functions array_intersect()
in an IF
statement, this way:
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_pickup_shipping_methods', 10, 1 );
function custom_discount_for_pickup_shipping_methods( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only on checkout page
if ( is_checkout() ) {
// Here below define your allowed shipping methods rate Ids in this array
$allowed_shipping_methods = array('local_pickup:63', 'local_pickup:64', 'local_pickup:65', 'local_pickup:66', 'local_pickup:67', 'local_pickup:68', 'local_pickup:69');
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
// Only for Local pickup chosen shipping method
if ( count( array_intersect($allowed_shipping_methods, $chosen_shipping_methods) ) > 0 ) {
// Discount percentage
$percentage = 5;
// Calculate discount
$discount = $cart->get_subtotal() * $percentage / 100;
// Add the discount
$cart->add_fee( $percentage . __('% afhaalkorting, levering vanuit ons magazijn'), -$discount );
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.