Iam trying to trigger a popup by simulating a button click with a simple JS function when a product from a specific category is added to the woocommerce cart. I have seen some do it in simmilair functions, but I cant figure this one to work.
I have composed the following function that runs if the category is in cart and if the page is the checkout page:
add_action( 'woocommerce_before_checkout_form', 'check_category_in_cart' );
function check_category_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
<script>
jQuery(document).ready(function($) {
$('#pop-up').trigger('click');
});
</script>
}
}
This function makes my website not function. Anyone has an idea how I can get this to work?
3
Answers
use setTimeout(). try the below code.
PHP waits for a php valid code in
<?php ?>
tags, but you are placing JavaScript, so you have to close the PHP tag before<script>
and open a new one after the</script>
. Otherwise your jQuery code is fine.Reason need to check.
if all is good then you can try.
This will work if your Id not found once your id placed then this will stop the timer and trigger pop-up.
Thanks.