WooCommerce 促销折扣:买 10 送 1

WooCommerce promotional discount: Buy 10 Get 1 Free

我正在尝试为三种可变产品(464、465 和 466)设置特定折扣。如果客户购买十件产品,他们将免费获得一件。

基于 答案代码,我想出了以下代码:

add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_11th_at_100', 10, 1 );
function add_custom_discount_11th_at_100( $wc_cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    $discount = 0;
    $items_prices = array();

    // Set HERE your targeted variable product ID
    $targeted_product_id = 464;

    foreach ( $wc_cart->get_cart() as $key => $cart_item ) {
        if( $cart_item['product_id'] == $targeted_product_id ){
            $qty = intval( $cart_item['quantity'] );
            for( $i = 0; $i < $qty; $i++ )
                $items_prices[] = floatval( $cart_item['data']->get_price());
        }
    }
    $count_items_prices = count($items_prices);
    if( $count_items_prices > 10 ) foreach( $items_prices as $key => $price )
        if( $key % 11 == 1 ) $discount -= number_format($price / 1, 11 );

    if( $discount != 0 ){
        // Displaying a custom notice (optional)
        wc_clear_notices();
        wc_add_notice( __("Buy 10 Get 1 Free"), 'notice');

        // The discount
        $wc_cart->add_fee( 'Buy 10 Get 1 Free', $discount, true  );
        # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
    }
}

但它只适用于一个产品 ID。我如何扩展它以适用于三个产品 ID?

要使其适用于多种产品,您可以使用 in_array() php 函数,如下所示:

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

    // Set HERE your targeted variable products IDs
    $targeted_product_ids = array( 464, 465, 466 );

    $each_n_items = 10; // Number of items required to get a free one
    $discount = 0; // Initializing
    $items_prices = array(); // Initializing 

    foreach ( $cart->get_cart() as $cart_item ) {
        if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
            $qty = intval( $cart_item['quantity'] );

            for ( $i = 0; $i < $qty; $i++ ) {
                $items_prices[] = floatval( $cart_item['data']->get_price() );
            }
        }
    }
    $count_items_prices = count($items_prices);

    if ( $count_items_prices > $each_n_items ) {
        foreach ( $items_prices as $key => $price ) {
            if ( $key % ($each_n_items + 1) == 1 ) {
                $discount += number_format($price, 2 );
            }
        }
    }

    if ( $discount > 0 ) {
        // Displaying a custom notice (optional)
        wc_clear_notices();
        wc_add_notice( __("Buy 10 Get 1 Free"), 'notice');

        // The discount
        $cart->add_fee( __("Buy 10 Get 1 Free"), -$discount, true  );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件,经过测试并有效。