1
votes

I am using this function to make my custom post type "portfolio" show up on archives/category/tag pages (in functions.php):

function namespace_add_custom_types( $query ) {
  if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array('post', 'portfolio'));
      return $query;
    }
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' 

The problem is that for some reason it is making my nav menu disappear. Here is the code for the nav menu (in header.php):

<?php wp_nav_menu(array( 'theme_location'  => 'primary', 'sort_column' => 'menu_order', 'menu_class' => 'nav-menu', 'container_class' => 'nav-menu',) ); ?>

Any idea what I can change?

2
Do you have any error in console ? - Brewal
Is the html of the menu present in the code ? - Brewal
All of the html from the menu just comes from wp_nav_menu(), it is then styled by css. No html is being outputted though. If I remove the function "namespace_add_custom_types" then the menu returns to working. - fender967
try commenting out the line: return $query; Does that make the menu re-appear? - Hugh Downer
No, it seems like it is just the line above that that is doing it. - fender967

2 Answers

7
votes

WordPress nav menus consist of posts of the nav_menu_item post type, and as your function changes the post type for all queries, there is nothing to display.

Solution: modify only the main query by checking is_main_query, e.g.:

if( is_category() && $query->is_main_query() ) {
    // do stuff
}

PS: pre_get_posts is an action hook, so you should use add_action instead of add_filter:

add_action( 'pre_get_posts', 'namespace_add_custom_types' );
0
votes

Add this: 'nav_menu_item' to the array in your functions.php file. Final code looks like this:

function namespace_add_custom_types( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'portfolio'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );