При дальнейшей проверке предметы, которые "проверяются", все еще называются с помощью ajax added_to_cart
.Поэтому та же самая логика может использоваться, когда код jQuery отправит запрос ajax на делегированное событие «Added_to_cart».По этому запросу php получит количество попыток добавления элемента корзины в корзину и вернет его в jQuery.Если этот счетчик удовлетворяет условию, он отобразит сообщение-предупреждение:
Спасибо @LoicTheAztec за помощь в предоставлении части решения.
// remove the filter
add_filter( 'woocommerce_cart_redirect_after_error', '__return_false');
add_action( 'woocommerce_add_to_cart_validation', 'restrict_only_one_item_in_cart' );
function restrict_only_one_item_in_cart($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
if($item_count >= 20)
{
//WE WILL EXECUTE JAVASCRIPT BELOW INSTEAD
return false;
}
return $cart_item_data;
}
// The Jquery script
add_action( 'wp_footer', 'cart_full' );
function cart_full() {
?>
<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'
},
success: function (response) {
if( response >= 20 ){
swal(
'Youve added the max items!',
'Change Your box',
'error'
);
}
}
});
});
});
</script>
<?php
}