So how can I give a 5% discount on total order cost if a customer chooses Local Pickup shipping method? I tried this code in Woocommerce:
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;
$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' ) !== false ) {
// Calculate the discount
$discount = $cart->get_subtotal() * $percentage / 100;
// Add the discount
$cart->add_fee( __('Pickup discount') . ' (' . $percentage . '%)', -$discount );
}
}
But I get an error saying: [NOTICE] [96575] [STDERR] PHP Warning: Undefined array key "query" in /wp-content/plugins/code-snippets/php/snippet-ops.php on line 623\n
It's about this line here:
$chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
I have searched google for other codes and found this one from here (https://wpsimplehacks.com/wocommerce-how-to-give-a-discount-to-local-pickup/):
// Add Percentage Discount to Local Pickup in Woocommerce
function local_pickup_discount( $cart ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_no_ajax = $chosen_methods[0];
if ( 0 === strpos( $chosen_shipping_no_ajax, 'local_pickup' ) ) {
$discount = $cart->subtotal *0.05; // Set your percentage. This here gives 15% discount
$cart->add_fee( __( 'Afhaalkorting', 'yourtext-domain' ) , -$discount ); // Change the text if needed
}
}
add_action( 'woocommerce_cart_calculate_fees', 'local_pickup_discount');}
The error is gone but the 0.05 is not correct. It says: 5% of 299 = 280,91, (=-18,09) but it should be 284,05 (=-14,95). Something to do with taxes maybe?
How can I get a code that works?