Скидка корзины WooCommerce от второго товара только на обычные товары - PullRequest
1 голос
/ 04 мая 2020

Я нашел этот фрагмент кода в stackoverflow, он делает то, что мне нужно, за исключением того, что мне нужно применить скидку -5 € на каждый продукт сразу после добавления 2 продуктов в корзину.

Пример:

  • за 1 товар в корзине пользователь получит 0 € скидку
  • за 2 товара в корзине пользователь получит 5 € скидку
  • за 3 товара в корзина, пользователь получит скидку 10 €
  • на 4 товара в корзине, пользователь получит скидку 15 €
  • на 5 товаров в корзине, пользователь получит скидку 20 €

и так далее ...

add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
    // if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    // Only when there is 2 or more items in cart
    if( $cart->get_cart_contents_count() >= 2):

        // Initialising variable
        $is_on_sale = false;

        // Iterating through each item in cart
        foreach( $cart->get_cart() as $cart_item ){
            // Getting an instance of the product object
            $product =  $cart_item['data'];

            // If a cart item is on sale, $is_on_sale is true and we stop the loop
            if($product->is_on_sale()){
                $is_on_sale = true;
                break;
            }
        }

        ## Discount calculation ##
        // fixed reduction price
        $reduction = 5;


        ## Applied discount (no products on sale) ##
        if(!$is_on_sale )
            $cart->add_fee( '-5€ à partir du 2ème article commandé', -$reduction);

    endif;
}

Любая помощь приветствуется.

Ответы [ 2 ]

3 голосов
/ 04 мая 2020

Вам лучше использовать следующее, в котором будут учитываться только обычные товары (не в продаже), и будет применяться скидка на основе указанного количества c, начиная со 2-го предмета:

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

    // Initialising variable
    $regular_items_count = -1;

    // Iterating through each item in cart
    foreach( $cart->get_cart() as $cart_item ){

        // Count only on regular items (not "on sale" items)
        if( ! $cart_item['data']->is_on_sale() ){
            $regular_items_count += $cart_item['quantity'];
        }
    }

    // Only for regular items starting on the 2nd item (not "on sale" items)
    if ( $regular_items_count > 0 ) {

        // Progressive fixed discount calculation on regular items only
        $discount = 5 * $regular_items_count;


        // Apply a discount for "on sale" items only 
        $cart->add_fee( __("-5€ à partir du 2ème article commandé", "woocommerce"), -$discount );
    }
}

Код входит в функции. php Файл вашей активной дочерней темы (или активной темы). Протестировано и работает.


Некоторые похожие темы с похожими ответами :


Дополнение - исключая категорию продукта:

Заменить:

if( ! $cart_item['data']->is_on_sale() ){

на:

if( ! $cart_item['data']->is_on_sale() && ! has_term( array( 5537 ), 'product_cat', $cart_item['product_id'] ) ) {
1 голос
/ 04 мая 2020

Ты так близко. Вы знаете количество товаров в корзине $cart->get_cart_contents_count() и хотите, чтобы скидка начиналась после первого товара.

Замените $reduction = 5;

на $reduction = 5*($cart->get_cart_contents_count() - 1);

Ваш полный код должен выглядеть следующим образом:

add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
    // if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    // Only when there is 2 or more items in cart
    if( $cart->get_cart_contents_count() >= 2):

        // Initialising variable
        $is_on_sale = false;

        // Iterating through each item in cart
        foreach( $cart->get_cart() as $cart_item ){
            // Getting an instance of the product object
            $product =  $cart_item['data'];

            // If a cart item is on sale, $is_on_sale is true and we stop the loop
            if($product->is_on_sale()){
                $is_on_sale = true;
                break;
            }
        }

        ## Discount calculation ##
        // fixed reduction price
        $reduction = 5*($cart->get_cart_contents_count() - 1);


        ## Applied discount (no products on sale) ##
        if(!$is_on_sale )
            $cart->add_fee( '-5€ à partir du 2ème article commandé', -$reduction);

    endif;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...