Woocommerce-购物车中有X单位Y产品如何打折?

时间:2020-08-25 00:47:14

标签: php woocommerce

背景

我已经尝试了许多免费插件和一个付费插件。到目前为止,即使付费插件本来可以解决问题,但仍然没有任何效果。我认为插件冲突打破了它。该插件还为网站增加了很多膨胀。

因此,我认为通过一些代码执行此操作会更流畅,更高效。

我要实现的目标

  1. 这可能适用于一种或多种产品。这些将在代码中指定为变量。目前,我只需要一种产品,所以,如果这要简单得多,那么只将其与一种产品一起使用就可以了。
  2. 当购物车中有X个指定产品(由其变形的任意组合组成)时,该产品将获得$ Y折扣。例如,将从购物车总额中扣除$ Y。就我而言,我希望折扣适用于购物车中的3个单位。

注意:所有版本的价格都相同。

几乎有效的代码

有一个非常有用的答案here。它几乎完全符合我的要求。

我将该代码更改为以下代码:

add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_on_qty', 10, 1 );
function add_custom_discount_on_qty( $cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // YOUR SETTINGS:
    $targeted_product_id = 8925; // Set HERE your targeted product ID
    $discount_qty = 0; // Set discount break point
    $discount_amt = 7.5; // Set discount amount $Y
        
    // Initializing variables
    $discount = $qty_notice = 0;
    $items_prices = array();
    // Loop through cart items
    foreach ( $cart->get_cart() as $key => $cart_item ) {
        if( in_array( $targeted_product_id, [$cart_item['product_id'], $cart_item['variation_id']] ) ){
            $quantity = (int) $cart_item['quantity'];
            $qty_notice += $quantity;
            for( $i = 0; $i < $quantity; $i++ ) {
                $items_prices[] = floatval( $cart_item['data']->get_price());
            }
        }
    }

    $count_items = count($items_prices); // Count items

    rsort($items_prices); // Sorting prices descending order

    if( $count_items > $discount_qty ) {
        foreach( $items_prices as $key => $price ) {
            if( $key % 2 == 1 )
                $discount -= $discount_amt;
        }
    }

    // Applying the discount
    if( $discount != 0 ){
        $cart->add_fee('3x Face Mask Discount', $discount );

        // Displaying a custom notice (optional)
        wc_clear_notices(); // clear other notices on checkout page.
        if( ! is_checkout() ){
            wc_add_notice( __("You get the 3 Face masks for $49.50 deal"), 'notice');
        }
    }
    //  Display a custom notice on cart page when quantity is equal to 2.
    elseif( $qty_notice == $discount_qty ){
        wc_clear_notices(); // clear other notices on checkout page.
        if( ! is_checkout() ){
            wc_add_notice( __( "Add one more Face mask to get 3 for $49.50" ), 'notice');
        }
    }
}

我需要什么帮助

在上面的代码中,我不了解一个问题,以及如何实现一项附加要求:

  1. 我将这行代码$discount -= number_format( $price / 2, 2 );更改为$discount -= $discount_amt;$discount_amt设置为$ 7.50,因此,我希望从购物车总额中扣除该费用。但是,当购物车中有超过三个单位的产品时,这将导致不稳定的结果。如果再加上一个,折扣将增加到$ 15。如果再加上五分之一,则仍为15美元。如果我增加第六个,则增加到$ 22.50。我不清楚为什么会这样。

  2. 理想情况下,我希望该函数的计算稍微复杂一点。我想要的是,如果有X($discount_qty)的倍数,则折扣也将倍数。因此,如果X = 3,则购物车中有3个单位时,购物车将获得$ Y折扣。如果有4或5个单位,则折扣将保持在$ Y。但是,如果有6个单位(X 2),则折扣将增加一倍($ Y 2)。

非常感谢您能解决上述问题(1)和要求(2)。

0 个答案:

没有答案