I have a menu item that points to the cart and that reads the number of products currently in the cart.
CART (3)
When, on the cart page, I change the number of products and click the "Update cart"
button, or delete an item, the number doesn't refresh.
Any idea why?
/*CHANGE CART MENU TITLE IN MENU*/
add_filter( 'wp_setup_nav_menu_item','my_item_setup' );
function my_item_setup($item) {
if ( ! is_admin() ) {
if ( class_exists( 'woocommerce' ) ) {
global $woocommerce;
if ( $item->url == esc_url( wc_get_cart_url() ) ) {
if (is_null($woocommerce->cart)){
} else {
if( get_locale() == 'fr_FR' ) {
$item->title = 'PANIER ('. '<span class="count-cart">' . $woocommerce->cart->get_cart_contents_count() . '</span>)';
} else {
$item->title = 'MY CART ('. '<span class="count-cart">' . $woocommerce->cart->get_cart_contents_count() . '</span>)';
}
}
}
}
}
return $item;
}
And
add_filter( 'woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments' );
function my_woocommerce_add_to_cart_fragments( $fragments ) {
// Add our fragment
$fragments['li.menu-item-type-woocommerce-cart'] = my_item_setup( '');
return $fragments;
}
EDIT:
Using Ajaxify the cart items count in Woocommerce answer code, seems to work a little better. The product number updates when I delete an item from the cart page, or when I change the number of items, but it doesn't update when I empty the cart. Moreover, there's a space before and after the product number (see picture with empty cart and "CART ( 1 )"
.
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_cart_fragments');
function wc_refresh_cart_fragments($fragments){
ob_start();
?>
<span class="count-cart"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
<?php
$fragments['li a span.count-cart'] = ob_get_clean();
return $fragments;
}