Wordpress custom post type hierarchy and menu highlighting (current_page_parent)

Craig picture Craig · Jul 17, 2010 · Viewed 11.6k times · Source

I have created a custom post type of 'portfolio' and page with a template that retrieves all posts matching that custom post type.

The problem is when I drill down into the actual post, the post seems to sit under 'blog' in the main menu highlighting (displays current_page_parent as a class)

The permalink url is correct: www.site.com/portfolio/post-slug

But the menu thinks the parent is 'blog'.

This is obviously a hierarchical issue but I don't know what to do to fix it.

Answer

user11977 picture user11977 · Jul 17, 2010

It appears this is an issue with the core Wordpress code; the code that generates the menu classes adds current_page_parent to your Blog page everywhere except when viewing static page templates.

(This has been discussed in passing at http://core.trac.wordpress.org/ticket/13543).

You can however get around this with some custom code using the page_css_class filter. For example, add something along these lines to functions.php (not 100% tested):

function my_page_css_class($css_class, $page) {
    if (get_post_type()=='portfolio' || is_page(57)) {
        if ($page->ID == get_option('page_for_posts')) {
            foreach ($css_class as $k=>$v) {
                if ($v=='current_page_parent') unset($css_class[$k]);
            }
        }
        if ($page->ID==57) {
            $css_class[]='current_page_parent';
        }
    }
    return $css_class;
}
add_filter('page_css_class','my_page_css_class',10,2);

Replacing 57 with the ID of your portfolios page, of course. That removes current_page_parent when printing the blog page and adds current_page_parent to your portfolios page, when either viewing a single portfolio or viewing the portfolios page itself.