WooCommerce cart item count

User
get wooocommerc cart item count using ajax jquery in wp_footer hook alert
Assistant
You can use the `wp_footer` hook to include the necessary jQuery script in your WordPress theme to retrieve the WooCommerce cart item count using AJAX. Below is an example of how you can achieve this:

### PHP Code (Add in your theme's `functions.php` file or a custom plugin)

add_action('wp_footer', 'woo_cart_item_count_ajax_script');
function woo_cart_item_count_ajax_script() {
    if (function_exists('is_cart') && is_cart()) {
        return; // Avoid loading the script on the cart page
    }
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            // Define the AJAX call
            function getCartItemCount() {
                $.ajax({
                    url: "<?php echo admin_url('admin-ajax.php'); ?>",
                    type: "POST",
                    data: {
                        action: "get_cart_item_count"
                    },
                    success: function (response) {
                        alert("Cart Item Count: " + response);
                    },
                    error: function () {
                        alert("Failed to fetch cart item count.");
                    }
                });
            }

            // Trigger the function on page load
            getCartItemCount();
        });
    </script>
    <?php
}

add_action('wp_ajax_get_cart_item_count', 'get_cart_item_count');
add_action('wp_ajax_nopriv_get_cart_item_count', 'get_cart_item_count');
function get_cart_item_count() {
    // Ensure WooCommerce is active
    if (!class_exists('WooCommerce')) {
        wp_send_json_error('WooCommerce not active.');
        return;
    }

    // Get the cart item count
    $cart_count = WC()->cart->get_cart_contents_count();

    // Return the count as JSON
    wp_send_json($cart_count);
}

### How It Works
1. **AJAX Script in `wp_footer`:**
– This script uses jQuery to make an AJAX POST request to the WordPress `admin-ajax.php` endpoint.
– The `action` parameter specifies the server-side function to handle the request (`get_cart_item_count`).

2. **Server-Side Function:**
– The `get_cart_item_count` function retrieves the WooCommerce cart item count using `WC()->cart->get_cart_contents_count()`.

3. **Output:**
– The cart item count is sent as a JSON response and displayed in an alert box when the page loads.

### Testing
1. Add items to the cart.
2. Navigate to any page except the cart or checkout page.
3. An alert box will display the current cart item count.

Leave a Comment

Your email address will not be published. Required fields are marked *