要使其适用于 2 个不同的产品类别,当这些产品类别之一的 5 件商品已添加到购物车时显示 Sweet 警报:
// 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
?>
<script src="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/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) {
$.each( JSON.parse(response), function( category, count ) {
if( count == 5 ){
// Display javascript alert
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: "You've added 5 "+category+"!"
});
}
// The below line is just for testing: to be removed
console.log('category: '+category+' | count: '+count);
});
}
});
});
});
</script>
<?php
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。