[wp-hackers] Applying a filter to the main loop only

Mike Schinkel mikeschinkel at newclarity.net
Mon Jul 26 18:24:03 UTC 2010


On Jul 26, 2010, at 12:28 PM, Andrew Nacin wrote:
> On Mon, Jul 26, 2010 at 11:13 AM, John Blackbourn
>> wrote:
>> I'm writing a plugin which adds a filter to pre_get_posts but the
>> filter should only apply when we're dealing with the main WordPress
>> loop (ie. the one which is constructed using the query string). There
>> can potentially be several loops on any given page, and the main loop
>> may not be the first loop on the page (so I can't apply the filter and
>> then remove it at the end of the first loop).
>> 
>> How can I determine if the current loop is the "main" loop constructed
>> from the query string without having to touch the loop code in the
>> template?
> 
> Contrary to the advice of many a tutorial, the pre_get_posts hook is almost
> always the wrong hook to use here. Please look at the parse_request and
> request hooks, and also a wp-hackers thread from a few days ago titled
> "pre_get_posts problem".

Whether John uses pre_get_posts or parse_request/request he still has the same problem; how to tell which is the "main" loop?  It's a great "Best Practices" question, actually.

As we use WordPress for a lot more patterns besides just blogging there are emerging lots of use-cases that the global nature of some of these hooks makes difficult. I've struggled with figuring out to write robust code because it seems most of the time I'm just inspecting "artifacts" (i.e. testing some object property for some value that I discover it has in my use-cases but unsure or unaware if it will always be true.) Coming up with a set of "well known solutions" for these main hooks would be rather helpful.

For example, one solution that comes to mind for John is to use a static (or global) "flag" variable initially set to false or unset and then change it to flag that you've made it through the main query's loop.  But are there ever queries that may run before the main loop, and if so it will break this logic.

Back to John's question; how to determine if your hook is in the "main" loop; what artifacts does one inspect?

-Mike



More information about the wp-hackers mailing list