1

When I create a WP_Query it's automatically considered a "secondary query", but what if I replace my main query with a WP_Query? Can I set my WP_Query to be considered a "Main Query"?

The reason I say this is because I need to use pre_get_posts to do some filtering. My current logic looks like this:

if(isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'my_post_type')

The problem with the above logic is that I have 2 queries in the same template of the same post type but only one of them is my core query, the query I want to label as "Main Query" so I can use a conditional such as $query->is_main_query() to differentiate the two and filter accordingly.

1

This is an overly complicated approach. pre_get_posts will work for any query and there are numerous ways to control when/how the callback behaves:

  1. Add and remove the callback:

    function dummy_action($q) {
    
    }
    
    add_action('pre_get_posts','dummy_action');
    $q = new WP_Query(
      array(
        'post_type' => 'post'
      )
    );
    remove_action('pre_get_posts','dummy_action');
    
  2. Use a self-removing callback:

    function dummy_action($q) {
      remove_action('pre_get_posts','dummy_action');
    }
    
    add_action('pre_get_posts','dummy_action');
    $q = new WP_Query(
      array(
        'post_type' => 'post'
      )
    );
    
  3. Feed the query a parameter you can use as a trigger:

    function dummy_action($q) {
      if ($q->get('action_trigger')) {
        // do something
      }
    }
    
    add_action('pre_get_posts','dummy_action');
    $q = new WP_Query(
      array(
        'post_type' => 'post',
        'action_trigger' => true
      )
    );
    

You do not want to "assign" a secondary query as the main query. That will cause the same issues as caused by using query_posts(), which essentially does assign a secondary query as the main query.

  • See I usually run with Option 3 (similar) but was hoping there was a better way to go about it. This may be better as another question, but what exactly are the problems when you overwrite the main query? I know query_posts() is a run around to WP_Query but what inherit issues come with overwriting the main query with your own? – Howdy_McGee May 29 '14 at 6:24
  • 1
    WordPress depends on a number of globals, one of which is $wp_query. Anything that depends on that global will be effected if you clobber it. How much effect it has depends on the theme and the installed plugins, and on where in the page load you clobber the query. Just don't do it. – s_ha_dum May 29 '14 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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