微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在ajax上的JS警报添加到购物车中,用于Woocommerce中的特定产品类别计数

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

例如IF购物车包含5件“袋子”类别的商品 – 显示提醒.

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

> Display a sweet alert on AJAX add to cart for a specific Woocommerce cart product count


> Counting cart-items of specific product category

目前,下面的代码成功触发,但仅基于购物车中的产品数量.它忽略了产品类别规则:

循环浏览购物车项目并设置产品类别计数器:

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

使用jQuery,如果遇到类别计数,则显示JavaScript警报.

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

解决方法:

您的代码中存在一些错误错误.请尝试使用此重新访问的代码

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

代码位于活动子主题(或活动主题)的function.PHP文件中.经过测试和工作.

enter image description here

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

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐