Simpler Wordpress Navigation with Timber

The markup for navigation menus can be a real chore. It's very easy to let the markup get incredibly complicated with loops and ifs.

Wordpress menus provide a sizeable amount of functionality, but out of the box to even start to get a handle on things you're going to have to use a navwalker class. However, creating your front-end markup inside of PHP is always a big no-no in my book.

Luckily, there's Timber. If you know me, you know I love Timber. It brings the power of Twig to Wordpress, seperating your PHP controllers away from your views.

Therefore, your complicated menu... could still end up being a complicated menu, just in Twig. While Twig gives you a lot to do, it's still easy to get caught up in for loops and if statements and just end up with a mess of a Twig file. We've all been there.

I decided to solve that on a project at Base this week by going back to basics on a TimberMenu and moving to Macros. These files should give you everything you need to immediately drop a simple navigation into your theme and customise the classes. These Macros harness the full power of TimberMenus to provide a full nested navigation instantly ready for styling.

I'm using SmartMenus to provide a lot of the functionality in this instance, but the implementation of your menu is irrelevant in this scenario. By tweaking the classes on elements, you can alter the menu to your heart's content.

All this does is provide clean, usable markup with all the relevant classes from Wordpress for you to style up with CSS. Exactly what good markup should do.

Add this line to your add_to_context function in Timber, where 'menu' is your Wordpress nav (created with register_nav_menus):

$context['primary_menu'] = new TimberMenu('menu');

Then, add nav_macros.twig into your views. In your template files, import that file and call There's an example of that in navigation.twig below.

Here's the files:

← Home