WordPress function makes my menu disappear

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):

Read More
<?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?

Related posts

Leave a Reply

2 comments

  1. 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' );
    
  2. 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' );