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
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…