Skip to content

Instantly share code, notes, and snippets.

@macder
Last active November 17, 2017 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macder/3696dbc1a2250c9f7086510ed10c4881 to your computer and use it in GitHub Desktop.
Save macder/3696dbc1a2250c9f7086510ed10c4881 to your computer and use it in GitHub Desktop.
WordPress - Timber Menu: set an archive menu item to 'current' when location is a single post
<?php
/*
Suppose you have a custom content type called 'videos'
You have a menu item that points to the 'videos' archive page (http://yoursite.com/videos)
When on a single video page you want the 'videos' menu item to be styled as the current/active link
The following will make the Timber\MenuItem 'current' property to true on the archives menu item when on a single post
*/
// register the menu
function register_menus() {
register_nav_menu('primary',__( 'Primary Navigation', 'theme_slug' ));
}
add_action( 'init', 'register_menus' );
function add_to_timber_context($context) {
$context['primary_menu'] = array_map(function($item) {
if(is_single()){
$item->current = ($item->object === get_post_type()) ?: false;
}
return $item;
}, (new TimberMenu('primary'))->get_items());
return $context;
}
add_filter('timber_context', 'add_to_timber_context');
<div class="c-nav">
<nav class="c-nav__menu" role="navigation">
<ul class="c-nav__menu-list">
{% for item in items %}
<li class="c-nav__menu-item">
<a class="c-nav__menu-link {{ item.current ? 'active' : '' }}" href="{{ item.get_link }}">
{{ item.title }}
</a>
</li>
{% endfor %}
</ul>
</nav>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment