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 );
}
}
}
2
Answers
strpos() function supports only three arguments, you’re using it wrong. Try this:
First in WooCommerce you can have multiple shipping methods applied on a split cart, so an array 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()
withcount()
in anIF
statement, this way:Code goes in functions.php file of your active child theme (or active theme). Tested and works.