I had an interesting question from a user who wants to hide the cart item from the menu when cart is empty. This tutorial will only work if you are using the WooCommerce plugin.
I added the simple PHP snippets into my functions.php file. Here is the code
/** * Hiding the cart menu item when cart is empty * * @author Paul * @license GPL 2.0+ */ function paul_nav_menu_items( $items, $menu ) { //* get the cart page id $cart_page_id = get_option( 'woocommerce_cart_page_id' ); if( ! empty( $cart_page_id ) ) { foreach( $items as $key => $item ) { if( $item->object_id === $cart_page_id && WC()->cart->is_empty() ) { unset( $items[ $key ] ); //* removing the cart menu item from list } } } return $items; } add_filter( 'wp_get_nav_menu_items', 'paul_nav_menu_items', 10, 2 );
There have a filter wp_get_nav_menu_items which is returning the menu items as an array. I targeted this filter and removing the cart menu item from the list. WC()->cart->is_empty() method is checking that your cart/bag is empty or not. Using unset() PHP function I am removing a item from the existing array. Later I am returning the updated $items variable for next process. Try this code and let me know how it is working at your end.