Woocommerce удалить free_gift из кол-ва товаров в корзине - PullRequest
0 голосов
/ 22 ноября 2018

У меня есть функция, которая устанавливает максимальное количество заказов в корзине равным 16. Таким образом, пользователь не может оформить заказ с более чем 16 товарами.

Я также запускаю плагин, который добавляет ключ free_gift к$cart_item array при добавлении купона.

Проблема в том, что когда пользователь добавляет 16 элементов + free_gift = всего 17 элементов, что не позволяет оформить заказ.

Как удалитьfree_gift от добавления в число элементов корзины?

Пример:

  • Сделать так, чтобы корзина Woocommerce думала, что 16 товаров + 1 free_gift = 16 товаров
  • Заставьте Woocommerce корзину думать, что 12 элементов + 1 free_gift = 12 элементов

Мой код, который позволяет добавлять free_gifts сверх максимального значения 16, но не применяетсяМаксимальное правило 16 пунктов:

    // Set a maximum number of products requirement before checking out
add_action( 'woocommerce_check_cart_items', 'spyr_set_max_num_products' );
function spyr_set_max_num_products() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {

        $cart_num_products = 0;

        foreach ( WC()->cart->cart_contents as $cart_item_key => $cart_item ) {

            // HERE I AM TRYING TO SKIP AND PREVENT CART ITEMS OF FREE_GIFTS BEING COUNTED
            if ( isset( $cart_item['free_gift'] ) ) {
                continue;
            }

            // Count for regular products.
                   $cart_num_products++;
        }

        // Set the maximum number of products before checking out
        $maximum_num_products = 16;

        // Compare values and add an error is Cart's total number of products
        // happens to be less than the minimum required before checking out.
        // Will display a message along the lines of
        // A Maximum of 16 products is allowed before checking out. (Cont. below)   
        if( $cart_num_products > $maximum_num_products ) {
            // Display our error message
            wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>' 
                . '<br />Current number of snacks: %s.',
                $maximum_num_products,
                $cart_num_products ),
            'error' );
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 22 ноября 2018

Попробуйте следующее, чтобы удалить пользовательский бесплатный элемент из числа элементов корзины:

add_action( 'woocommerce_check_cart_items', 'max_allowed_cart_items' );
function max_allowed_cart_items() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {

        // Set the maximum number of products before checking out
        $max_items_count = 16;

        $cart_items_count = WC()->cart->get_cart_contents_count( );

        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( isset( $cart_item['free_gift'] ) ) {
                $cart_items_count -= $cart_item['quantity'];
            }
        }

        if( $cart_items_count > $max_items_count ) {
            // Display our error message
            wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>' 
                . '<br />Current number of snacks: %s.',
                $max_items_count,
                $cart_items_count ),
            'error' );
        }
    }
}

Код находится в файле function.php вашей активной дочерней темы (или активной темы).Должно работать.

0 голосов
/ 22 ноября 2018

Сначала проверьте, есть ли бесплатный товар в корзине.Когда вы подсчитываете элементы «-1» в своей функции до того, как к кассе станет доступной.

    function free_product_in_cart($free_product_id) {

        $free_product_cart_id = WC()->cart->generate_cart_id( $free_product_id );
        return WC()->cart->find_product_in_cart( $free_product_cart_id ); //Return true when the free product is in the cart

    }

Итак, вы обновите свою логику, чтобы проверить:

 if(free_product_in_cart(your product id) { 
       $free_item_space = 1;
 } else {
       $free_item_space = 0;
 }

 if( $cart_num_products > $maximum_num_products + $free_item_space) {
        // Display our error message
        wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>' 
            . '<br />Current number of snacks: %s.',
            $maximum_num_products,
            $cart_num_products ),
        'error' );
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...