Skip to content
Advertisement

Local pickup custom percentage discount in WooCommerce checkout

I am using Local pickup shipping option custom percentage discount in Woocommerce answer code to make local pickup discount of 2% on Woocommerce. So people who choose to pickup their order get a discount on their total amount. This code is great, but I would like to hide it on cart page, and to only show up on the checkout page. Now it shows on both pages.

I tried to change $cart to $checkout and I deleted rule 15 and 16 but that won’t work unfortunately. Does anyone point me on the right direction.

Advertisement

Answer

To make it active only on checkout page, use the following:

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 = 2; // <=== 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 );
        }
    }
}

Code goes in function.php file of your active child theme (active theme). Tested and works.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement