Last active
November 17, 2017 19:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment