I was trying to make a sidebar using mini-cart.php on woocommerce and so far im doing okay, but i wanted to trigger the sidebar after i click on "add to cart" button on page product.
I found Run javascript code after ajax add to cart event in Woocommerce answer and I made some changes to the code:
add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' );
function trigger_for_ajax_add_to_cart() {
?>
<script type="text/javascript">
(function($){
$('body').on( 'click', '.single_add_to_cart_button', function(){
$( ".open-side-cart" ).trigger( "click" );
});
})(jQuery);
</script>
<?php
}
What I want is to trigger the mini-cart.php
sidebar when the user clicks on the ".single_add_to_cart_button" class button, and it works. But as woocommerce reloads the page updating the mini-cart.php
, so the trigger works before reloading the page.
Is there a way to trigger after reloading the page?
2
Answers
Thanks @LoicTheAztec I found an solution.
In my case I was unable to trigger jQuery using
$ _POST ['add-to-cart']
.My solution was to use an alternative method, every time a product is added to the cart a message appears and says "(product name) added to the cart" the text appears inside a div with the class
.woocommerce-message
.using this method i created a trigger for every time this message appears will click on the class
.open-side-cart
and the side cart will appearThe code:
As you are not using Ajax add to cart, when product is added to cart the page reloads as product data is posted… Then you can check for
$_POST['add-to-cart']
to display the active part of your jQuery script, once the page is reloaded as follows:Code goes in functions.php file of the active child theme (or active theme). Tested and works.
In some cases you may need to add a delay, so in this case you can replace:
by the following code block: