WordPress pre_get_posts category filter removes custom menu items

So I have this site where you can see there are two menus, one next to the logo the other on top right;

http://www.ducklingfarm.com

Read More

They are created using this code in functions.php;

function register_my_menus() {
register_nav_menus(
  array(
  'header-menu' => __( 'Header Menu' ),
  'extra-menu' => __( 'Extra Menu' )
)
 );
 }
add_action( 'init', 'register_my_menus' );

and this is my code to use the menus;

<nav>
<?php wp_nav_menu(array( 'theme_location' => 'header-menu' ) ) ?>
</nav>

<nav id="ecommerce">
<?php wp_nav_menu( array( 'theme_location' => 'extra-menu' ) ); ?>
</nav>

And the menus work fine, except when you go to categories in the sidebar such as “Articles” or “Events”on the “Blog” page;

http://www.ducklingfarm.com/blog/

The blog page is a custom post type, and to make the category work, I added some code into functions.php, and the menus are not working properly since then. That code is;

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
if(is_category() || is_tag()) {
$post_type = get_query_var('post_type');
if($post_type)
    $post_type = $post_type;
else
    $post_type = array('post','Blog');
$query->set('post_type',$post_type);
return $query;
}
}

So I’m guessing there’s something wrong with the code. Please help me! I’d really appreciate it.

Best,
Jaeeun

I solved it by changing the last code to this;

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
if(is_category()  && $query->is_main_query()) {
$post_type = get_query_var('post_type');
if($post_type)
    $post_type = $post_type;
else
    $post_type = array('post','Blog');
$query->set('post_type',$post_type);
return $query;
}
}

Related posts

Leave a Reply

2 comments

  1. You may try this (No need for multiple if and $post_type = $post_type;)

    add_filter('pre_get_posts', 'query_post_type');
    function query_post_type($query) {
        if(is_category()  && $query->is_main_query()) {
            $query->set( 'post_type', array( 'post', 'Blog' ) );
        }
        return $query;
    }
    
  2. check this conditions before your stuff :

      if ($query->get('post_type') == 'nav_menu_item')
        return $query;
    

    like here :

        function wp32151_search_filter($query)
    {
        if ($query->get('post_type') == 'nav_menu_item')
            return $query;
    
        if ($query->is_search) {
            $query->set('post_type', 'shows');
        } 
    
        return $query;
    }
    
    add_filter('pre_get_posts', 'wp32151_search_filter');