JS alert on ajax add to cart for multiple product categories count in Woocommerce

后端 未结 1 1690
感情败类
感情败类 2021-01-28 18:16

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 w

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 19:00

    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:

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

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

    0 讨论(0)
提交回复
热议问题