[wp-hackers] pre_get_posts alternatives
Mike Schinkel
mikeschinkel at newclarity.net
Mon Sep 27 18:56:12 UTC 2010
On Mon, Sep 27, 2010 at 4:05 PM, scribu <mail at scribu.net> wrote:
> On Mon, Sep 27, 2010 at 4:20 PM, Christian Foster <
> christian.foster at gmail.com> wrote:
>
>> Hi,
>>
>> I am hooking into pre_get_posts to filter certain post types on
>> taxonomy templates however I have realised this is also affecting any
>> other get_posts. Is there an alternative that will only effect the
>> main loop?
>>
>
> You can check for the global $wp_query object:
>
> add_action( 'pre_get_posts', 'amp_filter' );
> function amp_filter( $query )
> {
> if ( $query === $GLOBALS['wp_query'] && is_tax('locations') ) {
> $query->set( 'posts_per_page', 25 );
> return $query;
> }
Unfortunately that logic will fail if someone is using rewindposts() or query_posts() in a theme(see [1].) Here are a pair of hooks that won't have that problem. Note that the "is_main_loop" property is not a standard property of the $wp_query object, it's something I added for this purpose:
add_action( 'parse_request', 'mytest_parse_request' );
function mytest_parse_request( $wp ) {
global $wp_query;
$wp_query->is_main_loop = true;
return $wp;
}
add_action( 'pre_get_posts', 'mytest_pre_get_posts' );
function mytest_pre_get_posts( $query ) {
if ( isset($query->is_main_loop) && $query->is_main_loop) {
$query->set( 'posts_per_page', 25 );
$wp_query->is_main_loop = false;
}
return $query;
}
Hope this helps.
-Mike
[1] http://codex.wordpress.org/The_Loop#Loop_Examples_2
More information about the wp-hackers
mailing list