Search code examples
phpwordpresswoocommercediscount

Set a percentage discount to Local pickup shipping method in Woocommerce


I have a WordPress site which uses WooCommerce plugin. I would like to offer buyer 5% reduction from cart total if they select local pickup as a shipping method.

I already tried - 5 * [qty] and it doesn't seem to be working.

I also tried -0.95 * [cost] with no luck

enter image description here enter image description here


Solution

  • I am using WooCommerce 3 and achieved the above result by writing a function inside the function.php of active theme.

    function prefix_add_discount_line( $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' ) ) {
    
        // Define the discount percentage
        $discount = $cart->subtotal * 0.05;
        // Add your discount note to cart
        $cart->add_fee( __( 'Collection discount applied', 'yourtext-domain' ) , -$discount );
      }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line');