Develop

WordPress: Add current_page_ancestor Class to Custom Post Type Menu Item

The Issue

Family Tree

fig 1.0 family tree

Let’s say you just registered a Custom Post Type in WordPress called “products” and have added the CPT archive page to your site’s main menu. If you’ve styled your menu to react to the .current_page_item class, then you will see the menu item change when you are at www.yoursite.com/products. This is the expected behavior and everything is working!

However, if you were to navigate to a single post within the Custom Post Type, there is no class on the parent menu item to allow you to target it if you wanted to add styles. In my case, I like to keep the parent item highlighted, so if someone is viewing www.yoursite.com/products/product-1 it makes sense to me that “Products” in the main menu would remain highlighted – the site visitor is STILL technically viewing products!

Solution

There is a simple function you can add to your functions.php file or to your functionality plugin if you’re using one:

function cpt_archive_classes( $classes , $item ){
    
    $post_type = get_post_type();

    if ( $item->url == '/'.$post_type ) {
        $classes = str_replace( 'menu-item-type-custom', 'menu-item-type-custom current_page_ancestor', $classes );
    }

    return $classes;
}

add_filter( 'nav_menu_css_class', 'cpt_archive_classes', 10, 2 );

Explaination

This function checks the post URL to see if it matches the current post type – in our example, it’s looking for /products. If this condition is true, it will run a str_replace to add the class current_page_ancestor (note that current_page_ancestor is a native WordPress class, so if you’ve styled it already you are all set). That’s it! Happy styling ;)

{ Respond }

Leave a Reply

Your email address will not be published. Required fields are marked *


Adding code to your comment? Wrap it in the following tag to use the syntax highlighter.