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 class="fal fa-shopping-cart" style="font-size:1.25em;"></i><span class="cart-basket d-flex align-items-center justify-content-center">'. '' . $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…)
2
Answers
It could be implemented by conditionally adding the inner
<span>
just ifget_cart_contents_count() > 0
:You can also use the
WC()
global core function to get the cart items to count and then make the condition based on the count.