How to Dynamically Update WooCommerce Header Cart Item Count Using Ajax?

Mary-Kate Olsen
Release: 2024-10-29 18:32:02
Original
680 people have browsed it

How to Dynamically Update WooCommerce Header Cart Item Count Using Ajax?

Ajaxify Header Cart Items Count in Woocommerce

Overview:

In Woocommerce, updating the header cart's item count upon adding/removing items can be achieved without page reloads using Ajax.

Solution:

1. HTML Markup for the Cart Count:

In your theme's header.php, add the following code to embed the cart count in an HTML tag with a unique ID or class:

<code class="html"><?php 
$items_count = WC()->cart->get_cart_contents_count(); 
?>
<div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div></code>
Copy after login

2. Code Implementation:

Next, add this code to your functions.php file or any plugin file:

<code class="php">add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_count');
function wc_refresh_mini_cart_count($fragments){
    ob_start();
    $items_count = WC()->cart->get_cart_contents_count();
    ?>
    <div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div>
    <?php
        $fragments['#mini-cart-count'] = ob_get_clean();
    return $fragments;
}</code>
Copy after login

This hook updates the "mini-cart-count" element with the updated count after adding items to the cart.

3. Optional jQuery Trigger:

If you wish to force the count update via jQuery, use either of these delegated events:

<code class="javascript">$(document.body).trigger('wc_fragment_refresh');</code>
Copy after login
<code class="javascript">$(document.body).trigger('wc_fragments_refreshed');</code>
Copy after login

The above is the detailed content of How to Dynamically Update WooCommerce Header Cart Item Count Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template