Skip to content

Instantly share code, notes, and snippets.

@petertwise
Last active May 6, 2020 07:35
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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