How to Ajaxify Header Cart Items Count in WooCommerce?

Patricia Arquette
Release: 2024-10-30 01:26:02
Original
774 people have browsed it

How to Ajaxify Header Cart Items Count in WooCommerce?

Ajaxify Header Cart Items Count in WooCommerce

Challenge

In a custom WooCommerce-integrated WordPress theme, an issue arose where a cart items count indicator displayed incorrect values after adding items. The culprit was adding a specific quantity of items to the cart, resulting in the indicator only incrementing by one.

Solution

To address this, we can leverage WooCommerce's dedicated woocommerce_add_to_cart_fragments action hook, which provides Ajax support for updating the cart items count.

Implementation

1. HTML and ID/Class

In the theme's header.php file, we define the HTML element that will display the cart count. It's important to assign a unique ID or class for easy targeting:

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

2. PHP Code

Next, we add a function to the functions.php file that uses the hook to update the cart count content dynamically:

<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

3. Ajax Update

If you require additional control with jQuery, consider using the wc_fragment_refresh or wc_fragments_refreshed events:

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

or

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

By implementing these changes, the cart items count indicator will accurately reflect the number of items in the cart, even when adding specific quantities of products.

The above is the detailed content of How to Ajaxify Header Cart Items Count in WooCommerce?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!