Find out how you can display WooCommerce cart in the navigation block (menu) conditionally using code.
The navigation block is responsible for displaying the menu in WordPress block themes (or classic themes that have been given support). It allows to display a list of items, which are nested blocks, and it has improved a lot in the last updates.
Although it is quite customizable from the user interface, it does not allow you to show or hide items conditionally. Fortunately, WordPress 6.1 version introduces a PHP filter that allows you to interact with the navigation block.
This opens up a lot of possibilities, such as adding the WooCommerce cart conditionally.
Let’s see how:
Snippet to add WooCommerce cart to menu conditionally
Make sure you are using a block theme (for example Twenty Twenty-Three) or, if you are using a classic theme, that you have given support to template parts and have a defined header.
Now, add the following code at the end of functions.php or in your functionality plugin:
In this code you use the
block_core_navigation_render_inner_blocks filter to add a button at the end of the menu when the user is on a WooCommerce product tab (
Or, in the second example, if you want it to be always displayed except on the home page.
The idea is that you use the conditional tag that works for you in each case (for example,
But you don’t have to limit yourself only to WordPress conditional tags, you can use other types of conditionals.
For example, if you want the cart to be displayed only if it is not empty, you can use this code:
In this case the cart block will not be displayed until at least one product is added.
You can see that having a filter to modify the navigation block gives you extra flexibility to what the user interface offers.
However, keep in mind that when using a PHP filter you have the limitation that you will only see the result in the web frontend, in the backend the changes will not be reflected.
As you can see, thanks to the new WordPress navigation block filter you can conditionally add items to the menu of any theme
In this case you add the WooCommerce cart, but the possibilities are immense. In future tutorials you will learn more ways to take advantage of it.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉