On a WordPress WooCommerce site I added a cart icon in the menu with the number of items it contains inside a circle, by putting the following code in the functions.php file:
/* Add cart to 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 = '<span style="position:relative;"><i style="font-size:1.25em;"></i><span >'. '' . $woocommerce->cart->get_cart_contents_count() . '</span></span>';
}
}
}
}
}
return $item;
}
/**
* Updates the content of the cart link via AJAX when adding an item */
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;
}
It works well but I would like the circle and the number not to appear when the cart is empty (currently circle appears with "0" in it in this case), only the cart icon, do you know if this is possible, and, if so, could you tell me the code that allows it?
Thanks for your help !
(and sorry for my bad english…)
CodePudding user response:
It could be implemented by conditionally adding the inner <span>
just if get_cart_contents_count() > 0
:
if( get_locale() == 'fr_FR' ) {
$innerBasket = '';
$count = $woocommerce->cart->get_cart_contents_count();
if ($count > 0) {
$innerBasket = '<span >' . $count . '</span>';
};
$item->title = '<span style="position:relative;"><i style="font-size:1.25em;"></i>' . $innerBasket . '</span>';
}