New API in 3.3: is_main_query()
There’s a nifty new method for WP_Query that is available in 3.3: is_main_query().
This enables someone to hook into pre_get_posts and modify only the main query. No more checking for suppress_filters (which was wrong), or comparing against $wp_the_query (complicated), or using query_posts() in a template.
is_main_query(), the function, will return true if the current $wp_query is also the main query. (As an example, this would be false after query_posts() is called but before wp_reset_query() is called.) This is consistent with existing conditional tags — for example, is_page() refers to the main query, while is_page() can also be called against any WP_Query object.
Quick example (YMMV) —
add_action( 'pre_get_posts', 'nacin_modify_query_exclude_category' );
function nacin_modify_query_exclude_category( $query ) {
if ( $query->is_main_query() && ! $query->get( 'cat' ) )
$query->set( 'cat', '-5' );
}
For more: #18677
Alex Mills 1:11 am on December 7, 2011 Permalink
For those that want to use this while maintaining capability for old versions of WordPress (which is lame, but whatever), check this out: https://gist.github.com/1297669#gistcomment-58619
Rafael 1:30 am on December 7, 2011 Permalink
And what about that discussion of is_blog(), is that to go in 3.3 or not yet?!?
Arnoud 1:37 am on December 7, 2011 Permalink
There is a trailing dot in the link to the ticket. Clicking it results in a 404.
Andrew Nacin 3:19 am on December 7, 2011 Permalink
Ah, thanks. It’s a bug in the P2 theme. It’s been reported (last week, actually).
Alex Mills 3:52 am on December 7, 2011 Permalink
I can’t reproduce. Hmm.
Lance Willett 3:43 pm on December 8, 2011 Permalink
We got the report—a fix is is the works.
@viper007bond I am able to reproduce.
Lance Willett 10:32 pm on December 8, 2011 Permalink
Found another bug. ^^ The auto-Trac link is catching a changeset out of Viper’s username.
This thread is quite productive so far.
Alex Mills 10:53 pm on December 8, 2011 Permalink
@lance Fixed the changeset linking issue by updating the regex to be in sync with the better regex that we use internally.
jeremyclarke 3:31 pm on December 8, 2011 Permalink
Great new method, definitely something I was dying for in the past that should help clean up some of the code out there once people use it.
BTW, found another error in P2
Clicking the like button when you are not logged in loads a login box that is hidden by the background. Screenshot.
Lance Willett 3:42 pm on December 8, 2011 Permalink
Thanks for that—looking into it.
Lance Willett 10:14 pm on December 8, 2011 Permalink
This layout bug is fixed now, thanks again.