在 WooCommerce 中选择 "local pickup" 时不要为打折产品提供折扣

Do not give discounts for on sale products when selecting "local pickup" in WooCommerce

我使用 答案代码,在购物车和结账时选择“本地取货”时会增加折扣。

我已将折扣设置为 20%。

如果产品已经打折,我如何更改此代码以从计算中排除产品?

例如,购物车中有 3 件商品:2 件商品有底价,1 件商品有折扣。如何确保选择“Local Pickup”时20%的折扣只适用于底价商品?

有什么帮助吗?

而不是使用$cart->get_subtotal()

$cart_item['line_subtotal']是加在$line_subtotal,如果产品不是is_on_sale()(打折)

/**
* 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 );