Last active
September 11, 2022 01:11
-
-
Save michaelaguiar/55168b87d2a0b7402293 to your computer and use it in GitHub Desktop.
Woocommerce: Update Mini Cart on Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Update Mini Cart | |
$.post( | |
woocommerce_params.ajax_url, | |
{'action': 'mode_theme_update_mini_cart'}, | |
function(response) { | |
$('#mode-mini-cart').html(response); | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mode_theme_update_mini_cart() { | |
echo wc_get_template( 'cart/mini-cart.php' ); | |
die(); | |
} | |
add_filter( 'wp_ajax_nopriv_mode_theme_update_mini_cart', 'mode_theme_update_mini_cart' ); | |
add_filter( 'wp_ajax_mode_theme_update_mini_cart', 'mode_theme_update_mini_cart' ); | |
?> |
Thanks, i love you
Is it working well @huuhung11299 ?
@ghost what error did you have? Sorry, didn’t notice your comment until now...
yes, it doesn't work. It seems that WP caches cart or something so after your code WP returns the not updated cart. Let's name this query as the first. However, if you create the new query (let's name as the second) and try to receive the new mini cart - the previous (from the first query) product is already in cart (so it seems the cart was updated later than needed).
Setting a timeout of 1 second on the ajax call works for me. I know it is hacky but...
$('.single_add_to_cart_button').click(function(){
"use strict";
setTimeout(() => {
$.post({
url: woocommerce_params.ajax_url, // The AJAX URL
data: {'action': 'heykate_update_mini_cart'}, // Send our PHP function
success: function(response){
$('#heykate-cart').html(response); // Repopulate the specific element with the new content
console.log(response)
}
});
}, 1000)
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does not work.