Using is_main_query in WordPress

Using is_main_query in WordPress

With WordPress 3.3 is_main_query() was included to let the developer determine the main query when modifying the global $wp_query variable.  Before, it was hard to determine the main query due to the number of queries being performed per page load.  This also can reduce using custom queries within the themes files.

Check the main query with is_main_query

The snippet below adds a callback to the ‘pre_get_posts’ action to include a custom post type in the main query on all pages except single posts and single pages.

Now the custom post type will show up on the home page and any archive page.  An additional check was made to ignore the custom post type’s archive page to avoid including the standard ‘post’ post type.

Published by


Product developer at WPEngine and runner from Hampshire, Illinois. I work with php a lot; Spending most of my time digging into source code to see how it all works. You can find me on Twitter @rfmeier.

Leave a Reply

Your email address will not be published. Required fields are marked *