Add a CSS class to an item when Woocommerce cart is empty

Viewed 3151

I am trying to hide my cart when it is empty, so I decided to add a CSS class to the cart HTML item when the cart is empty, here is my current code:

 function x_woocommerce_navbar_menu_item( $items, $args ) {
      if (WC()->cart->cart_contents_count == 0 ) {
       echo '<script type="text/javascript">
                    $(document).ready(function() {
                        $("#header_cart").addClass("zero"); 
                    });
               </script>';
      }

I am adding this to my functionts.php file

Am I missing anything?

3 Answers

I am posting here a solution which bases on Tristup answer, as his answer is not 100% correct which observed Yahya Hussein.

add_filter( 'body_class','shoppingCartNotEmpty' );
function shoppingCartNotEmpty( $classes ) {
    $classes[] = WC()->cart->get_cart_contents_count() ? 'shopping-cart-not-empty' 
                                                       : 'shopping-cart-empty';
    return $classes;
}

When the shopping cart is empty then the CSS class shopping-cart-empty is created, otherwise shopping-cart-not-empty is available.

Related