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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php //* do not include this line /** * 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.
A. says
I tried this code but unfortunately it doesn’t work. Empty cart is still showing in my header. No errors that I can tell, it just doesn’t seem to do anything. Using Astra with child theme. I put this code in functions.php and tested when logged in to WP and not logged in. Same result. Oh well, it was worth a shot 🙂
Michael says
It works great AND… it ends up throwing Fatal error: Uncaught Error: Call to a member function is_empty() on null
when visiting the Appearance, Menus page.
Paul says
I updated the code. Try the new code and let me know.
Peter says
Dear Paul – thanks, it works for me, though “woocommerce_cart_page_id” in my case is NOT the object_id, had to find that out manually and enter it in the code as a static number (or a string of digits, rather: “4261”).
che says
Looking for similar functionality to hide cart in secondary top menu if cart is empty. Above code did not work for me. Any suggestions? woodsmanjewelry.com