JS警告在ajax中添加了多个产品类别的购物车。

时间:2022-10-25 10:15:22

In Woocommerce I'm trying to display a JavaScript "Sweet alert" when a specific count of products in the cart from a specific product category is reached, AND another alert when a specific count of products from a secondary category is reached.

在Woocommerce中,我正在尝试显示一个JavaScript“Sweet alert”,当一个特定的产品类别的购物车中特定的产品数量到达时,并且在到达一个二级类别的特定产品数量时,就会发出另一个警报。

Items are added to the cart via AJAX which is why I want to use a JavaScript alert (Sweet alert).

项目通过AJAX添加到购物车中,这就是为什么我要使用JavaScript警报(Sweet alert)。

e.g.

如。

  1. IF cart contains 5 products from category "Bags" - Display alert bags.
  2. 如果购物车包含5个产品类别“袋子”-显示警告袋。
  3. IF cart contains 5 products from category "Shoes" - Display alert shoes.
  4. 如果购物车包含5个产品类别“鞋”-显示警告鞋。
  5. IF basket already has 5 bags and then 5 shoes are added - Display alert shoes, but NOT for bags as they are already in the basket
  6. 如果篮子里已经有了5个袋子,然后又增加了5个鞋子——显示提醒的鞋子,但不是袋子,因为它们已经在篮子里了

The code below can work for scenario 1 and 2, but does handle number 3.

下面的代码可以用于场景1和2,但是处理数字3。

I have been helped with this answer code to which works for a single product category:

我已经得到了这个答案代码的帮助,它适用于一个单一的产品类别:

// 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
}

How can I handle 2 different product categories?

我如何处理两个不同的产品类别?

Any help is appreciated.

任何帮助都是感激。

1 个解决方案

#1


3  

To make it work for 2 different product categories displaying a Sweet alert when 5 items from one of those product categories have been added to cart:

当其中一个产品类别的5个产品被添加到cart时,使其适用于两个不同的产品类别,显示甜蜜的警报:

// 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
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

代码功能。您的活动子主题的php文件(或活动主题)。测试和工作。

JS警告在ajax中添加了多个产品类别的购物车。

#1


3  

To make it work for 2 different product categories displaying a Sweet alert when 5 items from one of those product categories have been added to cart:

当其中一个产品类别的5个产品被添加到cart时,使其适用于两个不同的产品类别,显示甜蜜的警报:

// 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
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

代码功能。您的活动子主题的php文件(或活动主题)。测试和工作。

JS警告在ajax中添加了多个产品类别的购物车。