Skip to content

Instantly share code, notes, and snippets.

@michaelaguiar
Last active September 11, 2022 01:11
Show Gist options
  • Save michaelaguiar/55168b87d2a0b7402293 to your computer and use it in GitHub Desktop.
Save michaelaguiar/55168b87d2a0b7402293 to your computer and use it in GitHub Desktop.
Woocommerce: Update Mini Cart on Ajax
// Update Mini Cart
$.post(
woocommerce_params.ajax_url,
{'action': 'mode_theme_update_mini_cart'},
function(response) {
$('#mode-mini-cart').html(response);
}
);
<?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' );
?>
@huuhung11299
Copy link

Thanks, i love you

@michaelaguiar
Copy link
Author

Is it working well @huuhung11299 ?

@michaelaguiar
Copy link
Author

@ghost what error did you have? Sorry, didn’t notice your comment until now...

@dnshulga
Copy link

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).

@jpshayes
Copy link

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