0

I use Local pickup shipping option custom percentage discount in Woocommerce answer code that adds a discount when choosing "Local Pickup" in the cart and at checkout.

I have set the discount to 20%.

How can I change this code to exclude products from calculations if they are already at a discount?

For example, there are 3 products in the cart: 2 products with a base price and 1 product with a discount. How to make sure that a 20% discount when choosing "Local Pickup" applies only to products with a base price?

Any help?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Dmitry
  • 119
  • 1
  • 9
  • 38

1 Answers1

2

Instead of using $cart->get_subtotal()

$cart_item['line_subtotal'] is added to the $line_subtotal, if the product is not is_on_sale() (discount)

/**
* Discount for Local Pickup
*/
function custom_discount_for_pickup_shipping_method( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 20; // 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 ) {

        // Set variable
        $new_subtotal = 0;

        // Loop though each cart items and set prices in an array
        foreach ( $cart->get_cart() as $cart_item ) {

            // Get product
            $product = wc_get_product( $cart_item['product_id'] );

            // Product has no discount
            if ( ! $product->is_on_sale() ) {
                // line_subtotal
                $line_subtotal = $cart_item['line_subtotal'];

                // Add to new subtotal
                $new_subtotal += $line_subtotal;
            }
        }

        // Calculate the discount
        $discount = $new_subtotal * $percentage / 100;

        // Add the discount
        $cart->add_fee( __('Discount') . ' (' . $percentage . '%)', -$discount );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_pickup_shipping_method', 10, 1 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
  • Thank you so much! Everything works great! Tell me, how can I make a notice for customers "The discount for pickup does not apply to products with a discount"? – Dmitry Apr 28 '20 at 19:24
  • Use: `wc_print_notice()`, see in the following example how this was used: https://stackoverflow.com/a/56235957/11987538 - `add_action( 'woocommerce_cart_calculate_fees', 'add_custom_surcharge', 10, 1 );` – 7uc1f3r Apr 29 '20 at 07:36