I'm using Elementor (Pro) for a WooCommerce website where I added an icon widget to the header and a HTML element next to it with CSS to show to cart count which will update via Ajax when add/remove items to/from the cart.
It works as desired, when I add an item the number increase, and when I remove an item the numbers decreases.
But my problem is that the element is also visible when there's nothing in the cart. It just shows the number 0. How can I hide it?
This is my code:
add_filter( 'woocommerce_add_to_cart_fragments', 'dwd_cart_count_fragments', 10, 1 );
function dwd_cart_count_fragments( $fragments ) {
$fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>';
return $fragments;
}
And this the html element:
<div class="dwd-cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></div>
And the CSS:
.dwd-cart-count {
position: absolute;
top: 10px;
right: 2px;
transform: translateY(-105%) translateX(25%);
font-family: Arial, Helvetica, sans-serif;
font-weight: normal;
font-size: 10px;
line-height: 20px;
height: 20px;
width: 20px;
vertical-align: middle;
text-align: center;
color: #fff;
background: #99c001;
border-radius: 50%;
padding: 1px;
}
I think I need an extra function before the filter. Something like this but can't get it to work:
function dwd_cart_count() {
$cart_count = WC()->cart->get_cart_contents_count();
if ( $cart_count > 0 ) {
?>
<span class="dwd-cart-count"><?php echo $cart_count; ?></span>
<?php
}
}