JS alert на ajax добавить в корзину для нескольких категорий товаров в Woocommerce - PullRequest
0 голосов
/ 27 мая 2018

В Woocommerce я пытаюсь отобразить «сладкое оповещение» JavaScript при достижении определенного количества продуктов в корзине из определенной категории продуктов И еще одно предупреждение при достижении определенного количества продуктов из вторичной категории.

Товары добавляются в корзину через AJAX, поэтому я хочу использовать предупреждение JavaScript (Sweet alert).

например

  1. ЕСЛИ корзина содержит 5 товаров из категории " Сумки " - Показать оповещения о сумках.
  2. ЕСЛИ в корзине 5 товаров из категории " Обувь "- Отображать предупреждающие ботинки.
  3. ЕСЛИ в корзине уже есть 5 сумок и , то добавляется 5 ботинок - Отображать предупреждающие ботинки, но НЕ для сумок, поскольку они уже находятся вкорзина

Приведенный ниже код может работать для сценария 1 и 2 , но обрабатывает номер 3 .

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

// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_items', 'checking_cart_items' );
add_action( 'wp_ajax_checking_items', 'checking_cart_items' );
function checking_cart_items() {
    if( isset($_POST['id']) && $_POST['id'] > 0 ){
        // Initialising variables
        $count      = 0;
        $product_id = $_POST['id'];
        $category   = 'bags';
        $category   = 't-shirts';

        // Loop through cart for product category
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
               $count += $cart_item['quantity'];
//ELSE IF STATEMENT HERE?
            }
        }

        // Only if the added item belongs to the defined product category
        if( has_term( $category, 'product_cat', $_POST['id'] ) )
            echo $count; // Returned value to jQuery
    }

    die(); // To avoid server error 500
}

// The Jquery script
add_action( 'wp_footer', 'items_check' );
function items_check() {
    if(is_checkout()) return; // Except on checkout page
    ?>
    <script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
    <script type="text/javascript">
    jQuery( function($){
        // wc_add_to_cart_params is required to continue
        if ( typeof wc_add_to_cart_params === 'undefined' )
            return false;

        $(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
            // The Ajax request
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'checking_items',
                    'id'    : $button.data( 'product_id' ) // Send the product ID
                },
              //ONLY DISPLAY ALERT IF TOTAL ITEMS IS FROM CATEGORY BAGS
                success: function (response) {
                    console.log('response: '+response); // Testing: to be removed
                    if(response == 5 ){
                        //DISPLAY JAVASCRIPT ALERT
                        const toast = swal.mixin({
                          toast: true,
                          showConfirmButton: false,
                          timer: 3000
                        });
                        toast({
                          type: 'success',
                          title: '5 Items Added!'
                        })
                    }
                }
            });
        });
    });
    </script>
    <?php
}

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

Любая помощьценится.

1 Ответ

0 голосов
/ 28 мая 2018

Для того, чтобы он работал для 2 разных категорий товаров, отображается предупреждение Sweet, когда в корзину было добавлено 5 товаров одной из этих категорий товаров:

// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_items', 'checking_cart_items' );
add_action( 'wp_ajax_checking_items', 'checking_cart_items' );
function checking_cart_items() {
    if( isset($_POST['id']) && $_POST['id'] > 0 ){
        // Initialising variables
        $counts     = array();
        $product_id = $_POST['id'];
        $categories = array('bags', 'shoes');

        // Loop through cart for product categories count
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $categories[0], 'product_cat', $cart_item['product_id'] ) )
               $counts[0] += $cart_item['quantity'];
            if ( has_term( $categories[1], 'product_cat', $cart_item['product_id'] ) )
               $counts[1] += $cart_item['quantity'];
        }

        // Return the product category count that belongs to the added item
        if( has_term( $categories[0], 'product_cat', $product_id ) )
            echo json_encode(array( strtoupper($categories[0]) => $counts[0])); // Returned value to jQuery
        if( has_term( $categories[1], 'product_cat', $product_id ) )
            echo json_encode(array( strtoupper($categories[1]) => $counts[1])); // Returned value to jQuery
    }

    die(); // To avoid server error 500
}

// The Jquery script
add_action( 'wp_footer', 'items_check' );
function items_check() {
    if(is_checkout()) return; // Except on checkout page
    ?>
    <script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
    <script type="text/javascript">
    jQuery( function($){
        // wc_add_to_cart_params is required to continue
        if ( typeof wc_add_to_cart_params === 'undefined' )
            return false;

        $(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
            // The Ajax request
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'checking_items',
                    'id'    : $button.data('product_id') // Send the product ID
                },
              //ONLY DISPLAY ALERT IF TOTAL ITEMS IS FROM CATEGORY BAGS
                success: function (response) {
                    $.each( JSON.parse(response), function( category, count ) {
                        if( count == 5 ){
                            // Display javascript alert
                            const toast = swal.mixin({
                              toast: true,
                              showConfirmButton: false,
                              timer: 3000
                            });
                            toast({
                              type: 'success',
                              title: "You've added 5 "+category+"!"
                            });
                        }
                        // The below line is just for testing: to be removed
                        console.log('category: '+category+' | count: '+count);
                    });
                }
            });
        });
    });
    </script>
    <?php
}

Код помещается в файл function.php вашего активногодетская тема (или активная тема).Проверено и работает.

enter image description here

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