Skip to content
All gists
Back to GitHub
Sign in
Sign up
Sign in
Sign up
{{ message }}
Instantly share code, notes, and snippets.
petertwise
/
active-cpt-menu-trail.php
Last active
May 6, 2020 07:35
Star
1
Fork
1
Star
Code
Revisions
2
Stars
1
Forks
1
Embed
What would you like to do?
Embed
Embed this gist in your website.
Share
Copy sharable link for this gist.
Clone via HTTPS
Clone with Git or checkout with SVN using the repository’s web address.
Learn more about clone URLs
Download ZIP
On the single view of any WordPress custom post type item, make the archive menu item for that post type active
Raw
active-cpt-menu-trail.php
This file contains 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
Show hidden characters
<?php
// on the single view of any custom post type item, make the archive menu item for that post type active
// set the global scope variables
$current_menu_parent = null;
$current_menu_item = null;
// STEP 1: loop through all the menu items and find the current and parent items
function squarecandy_active_items_prepare( $classes ) {
// get all the menu items
$menu = wp_get_nav_menu_items( 'main-menu' ); // insert your menu slug here
global $post;
global $current_menu_parent;
global $current_menu_item;
// loop through the menu items
foreach ( $menu as $menu_item ) {
$archive_link = get_post_type_archive_link( $post->post_type );
$menu_item_url = $menu_item->url;
$base_url = get_site_url();
// when you hit the item that matches the post type archive, save the current menu item and parent menu item.
if ( $archive_link === $menu_item_url || $archive_link === $base_url . $menu_item_url ) {
$current_menu_parent = (int) $menu_item->menu_item_parent;
$current_menu_item = (int) $menu_item->ID;
}
}
// unrelated to the above, but required to keep body_class working correctly
return $classes;
}
add_filter( 'body_class', 'squarecandy_active_items_prepare', 99, 1 );
// STEP 2: apply the current and parent classes as appropriate
function squarecandy_active_item_classes( $classes = array(), $menu_item = false ) {
global $post;
global $current_menu_parent;
global $current_menu_item;
if ( $menu_item->ID === $current_menu_parent ) {
$classes[] = 'current-menu-ancestor';
}
if ( $menu_item->ID === $current_menu_item ) {
$classes[] = 'current-menu-item active';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'squarecandy_active_item_classes', 10, 2 );
Sign up for free
to join this conversation on GitHub
. Already have an account?
Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.