Tag Archives: main query

It’s this the main query?

The main query in a WordPress site is the query based on the URL being accessed. When you access this post’s single page, the URL indicates the main query is the text you are reading right now. The “Recent Posts” widget on the sidebar is generated from a query, but not the main query.

There are a few methods to test for the “main query”. As of WordPress 3.3, there is a new way:


Examples: Using pre_get_posts hook | Using posts_where hook

There’s the old way (which is the basis for the above method):

In situations where I wanted to alter the content of a post (in the loop) if it was the main query, the above methods didn’t work reliably. I attempted to hook into the pre_get_posts action and set a global variable, which I would then test in the content filter function. I reasoned that the variable would be set to true before the loop, and then set to false if another query was called after that. The results however were always false.

My solution was to set a global variable with the post ID in a wp_head action, then test that against the post ID while in the loop (every time the_content filter is called.) Code below…

Now it’s quite possible this is not the most direct, efficient or reliable method. I welcome your comments if you have suggestions or concerns.