1

In Woocommerce I'm trying to display a JavaScript "Sweet alert" when a specific count of products in the cart from a specific category is reached. Items are added to the cart via AJAX which is why I want to use a JavaScript alert (Sweet alert).

e.g. IF cart contains 5 products from category "Bags" - Display alert.

I have researched and found the following helpful answers and used them to build out my code. However, I am struggling with applying the rule to only count products from a specific category.

At the moment, the code below successfully triggers, but only based on the number of products in the cart. It ignores the product category rule:

Loop Through cart items and set the product category counter:

// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_items', 'checking_items' );
add_action( 'wp_ajax_checking_items', 'checking_items' );
function checking_items() {

  global $woocommerce, $product;
                $i=0;         
                // Set minimum product cart total
                $total_bags = 0;
                $total_shoes = 0;

    if( isset($_POST['added'])){
        // Loop through cart for product category
        foreach ( $woocommerce->cart->cart_contents as $product ) :
                    if ( has_term( 'bags', 'product_cat', $product['22'] ) ) {
                       $total_bags += $product['quantity'];
                    } else {
                       $total_shoes += $product['quantity'];
                    }
                endforeach;
    }
    die(); // To avoid server error 500
}

Using jQuery, if count of category met, display JavaScript alert.

 // The Jquery script
add_action( 'wp_footer', 'item_check' );
function item_check() {
    ?>
    <script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
    <script type="text/javascript">
    jQuery( function($){
        // The Ajax function
        $(document.body).on('added_to_cart', function() {
            console.log('event');
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'checking_cart_items',
                    'added' : 'yes'
                },
              //ONLY DISPLAY ALERT IF TOTAL ITEMS IS FROM CATEGORY BAGS
                success: function ($total_bags) {
                    if($total_bags == 5 ){
//DISPLAY JAVASCRIPT ALERT
const toast = swal.mixin({
  toast: true,
  showConfirmButton: false,
  timer: 3000
});
toast({
  type: 'success',
  title: '5 Items Added!'
})
                    }
                }
            });
        });
    });
    </script>
    <?php
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hmm.. you are not returning anything from the checking_items() function – funkysoul May 27 '18 at 15:56
  • Do I need to explicitly return the variable?...I tried adding `return $total_bags;` after the IF in the function but didn't seem to change the behaviour of the `checking_items()` function –  May 27 '18 at 16:04

1 Answers1

2

There is some errors and mistakes in your code. Try this revisited code instead:

// 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'];
            }
        }

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

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

enter image description here

If you look on your browser inspector javascript console, you will see that ajax is working in the right way, returning each time the items count for that specific product category:

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Thanks @LoicTheAztec, I've tried the above code, but it doesn't seem to be working for me? The items add to cart successfully, however nothing triggers. I've looked at the inspector and I am getting `admin-ajax.php - 400 Bad Request` I do not get this error when the code is deactivated...I have never seen this error before? –  May 27 '18 at 17:28
  • 1
    @TheNattyProfessor I have retested the code just now, and it works perfectly… So there is something else like other code customizations, something in your theme or a plugin that is conflicting. – LoicTheAztec May 27 '18 at 17:35
  • Silly mistake, it was just my typo in the code - above example is working now! Just one question, it doesn't take into account if there is a second category? e.g. `IF category == bags, display alert 1....IF category == shoes, display alert 2` –  May 27 '18 at 18:21
  • I have published new question [here](https://stackoverflow.com/questions/50555448/js-alert-on-ajax-add-to-cart-for-multiple-product-categories-count-in-woocommerc) and also upvoted the links in my question here. Thanks for your help :) –  May 27 '18 at 18:52