How to disable the fallback feature for Timber\Menu?

50 Views Asked by At

In Timber, we can use Timber\Menu to make a standard WordPress menu available to the Twig template as an object. This replaces what the wp_nav_menu() do when developing WordPress themes.

WordPress will fallback menu to the lists of existing page if user don't assign. This can be disabled by passing the fallback_cp parameters to wp_nav_menu() like below:

wp_nav_menu(
    array(
        'theme_location' => 'primary',
        'fallback_cb'    => false, // Disables the fallback menu, which displays the pages added within your site.
    )
);

How can I disable such a fallback feature with Timber? I've read and search with keyword fallback in the document of Timber. There's nothing about it.

1

There are 1 best solutions below

0
Radek On

I think you should use conditions to achieve same functionality because of lacking support of fallback feature.

You can use the has_nav_menu() function to check if a menu is assigned to a specific theme location before rendering it in your template.

if( has_nav_menu( 'primary' ) ) {
    $context['menu'] = new Timber\Menu("primary");
}

Then in your Twig template, you can conditionally render the menu based on whether it exists in the context:

{% if menu %} 
   {% include "path/to/menu.twig" with {'menu': menu.get_items} %}
{% endif %}

This way, if no menu is assigned to the 'primary' theme location, no menu will be rendered, effectively disabling the fallback to a list of pages.