将 ajax 上的 JS 警报添加到购物车以获取 Woocommerce 中的特定产品类别计数

JS alert on ajax add to cart for specific product category count in Woocommerce(将 ajax 上的 JS 警报添加到购物车以获取 Woocommerce 中的特定产品类别计数)
本文介绍了将 ajax 上的 JS 警报添加到购物车以获取 Woocommerce 中的特定产品类别计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Woocommerce 中,当达到购物车中特定类别的特定产品数量时,我尝试显示 JavaScript甜蜜警报".商品通过 AJAX 添加到购物车,这就是我想使用 JavaScript 警报(甜蜜警报)的原因.

例如如果购物车包含 5 个产品,属于 Bags" 类别 - 显示警报.

我已经研究并找到了以下有用的答案,并使用它们来构建我的代码.但是,我正在努力将规则应用于仅计算特定类别中的产品.

  • 如果您查看浏览器检查器 javascript 控制台,您会看到 ajax 以正确的方式工作,每次为该特定产品类别计数时返回:

    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.

    • Display a sweet alert on AJAX add to cart for a specific Woocommerce cart product count
    • Counting cart-items of specific product 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
    }
    

    解决方案

    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.

    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:

    这篇关于将 ajax 上的 JS 警报添加到购物车以获取 Woocommerce 中的特定产品类别计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)