Disappearing Menus on Archive Pages in WordPress

15 Apr, 2014 | TipsWordpress TipsTechVfd

Having recently been building a new site using WordPress, which utilised the handy custom post type functionality, I came across a couple of problems when building my theme. I'm posting the solutions here in case they prove useful.

Getting Custom Post Types to Appears in the Archives

You can use a custom page to display an archive of you custom post types, but I just wanted a single template (it's a simple enough site). The problem is, only regular content types are included by default, so I used the code from CSS-Tricks:

[code lang="php"]function namespace_add_custom_types( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'your-custom-post-type-here'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );[/code]

That all worked lovely (modified to my data, obviously), but then I stumbled across a problem on the archive pages: my menu was disappearing. The Menu function is another I'm a fan of, due to the ability it provides to control your navigation, yet still access it via the control panel.


In this case, the problem was because of the function to include the custom post types, and I needed to modify the post_type array to include nav_menu_item (thanks to boyvanamstel's comment in this thread), to end up with:

[code lang="php"]function namespace_add_custom_types( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'your-custom-post-type-here', 'nav_menu_item'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );[/code]

And voila, my menu returned on the archive pages (there were several other methods I found, most of which were a bit too hacky).