Reputation: 580
I am trying to run javascript (Sweet Alert) on Woocommerce archive shop pages to execute only if there are 5 items in the cart & the page is equal to 'url/leanshop/'.
My add to cart functionality is using AJAX. The below code, sort of works...but I can't get it to trigger for the above conditions. It currently only triggers each time a product is added to the cart via AJAX.
My code so far:
add_action( 'wp_footer', 'items_in_cart_trigger' );
function items_in_cart_trigger() {
global $woocommerce;
// Set the minimum number of products in cart
$maximum_num_products = 5;
// Get the Cart's total number of products
$cart_num_products = WC()->cart->cart_contents_count;
// Compare values and if required amount of items in cart, display popup.
if( $cart_num_products == $maximum_num_products && is_page( '/leanshop/' ) ) {
?>
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
(function($){
$('body').on( 'added_to_cart', function(){
// Test output on JS console
console.log('added_to_cart');
// Call Sweet Alert PopUp Here
swal(
'You added all the items!',
'Proceed to checkout?',
'success')
});
})(jQuery);
</script>
<?php
}
}
UPDATE: The Javascript works with the following is_page() IF statement. So the problem is the logic above where I am trying to count the amount of items in the shopping cart and see if they are equal to a value, whilst on the shop archive page. Can anyone suggest the correct Woocommerce code logic in order to do so?
if( is_page('leanshop')) {
Upvotes: 2
Views: 1136
Reputation: 7027
Try:
if( $cart_num_products === $maximum_num_products && is_page( '/leanshop/' ) ) {
To test for equality, use triple equals (when same type) or double equals (when want to coerce type, but beware).
Upvotes: 2