Skip to content

Instantly share code, notes, and snippets.

@petertwise
Last active May 6, 2020 07:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save petertwise/19bcc3faf6552f29bac04670e4b081c4 to your computer and use it in GitHub Desktop.
Save petertwise/19bcc3faf6552f29bac04670e4b081c4 to your computer and use it in GitHub Desktop.
On the single view of any WordPress custom post type item, make the archive menu item for that post type active
<?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