Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have some functions into my pre_get_posts filter. So, the problem is that when I set a meta_query, all the menus disappear from the page.

function propersearchfilter($query) {
    $taxarray = array();
    $metaarray = array();

    array_push($metaarray , array(
        'key' => 'wpcf-market',
        'value' => 'forsell',
        'compare' => 'LIKE'
    ));

    $query->set('meta_query', $metaarray);
    return $query;
}
add_action('pre_get_posts', 'propersearchfilter', 1);
share|improve this question

2 Answers 2

That happens because pre_get_posts fires on every single instance of WP_Query. Posts get used for a lot of things in WordPress, including nav menus.

If you want to only modify the main query (the "loop") you can test for is_main_query.

<?php
add_action('pre_get_posts', 'wpse72969_modify_q');
function wpse72969_modify_q($q)
{
    if(!$q->is_main_query())
        return;

    // any calls to `set` here will modify ONLY the main query
}

You can also use any of the conditional tags as well:

<?php
add_action('pre_get_posts', 'wpse72969_modify_q2');
function wpse72969_modify_q2($q)
{
    if(!$q->is_main_query() || !$q->is_search())
        return;

    // any calls to `set` here will modify ONLY 
    // the main query on search pages.
}
share|improve this answer

pre_get_posts triggers for every query (front and admin side). It also triggers when querying nav-menu items (which is what is happening here).

Most of the time you only want to filter particular queries - so you need to check if that query is one you wish to modify.

Usually - and I think your example might be one - you only want to modify the 'main query'.

function wpse72969_pre_get_posts( $query) {
    //If its not the 'main query' don't do antying.
    if( !$query->is_main_query() )
        return;

    return $query; 
}
add_action('pre_get_posts', 'wpse72969_pre_get_posts');

More generally all the conditionals are available to you (Note: you want want to use the methods and not the functions: e.g. $query->is_search() as opposed to is_search().

You can even set custom variables to identify queries.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.