Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
}
like image 302
Jaeeun Lee Avatar asked Oct 05 '13 05:10

Jaeeun Lee


1 Answers

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;
}
like image 140
The Alpha Avatar answered Nov 09 '22 21:11

The Alpha