[wp-hackers] pre_get_posts problem

Michael D Adams mda at blogwaffe.com
Sat Jul 24 09:22:41 UTC 2010


On Tue, Jul 20, 2010 at 10:14 PM, Andrew Nacin <wp at andrewnacin.com> wrote:
> On Wed, Jul 21, 2010 at 12:57 AM, Angelia Baladon
> <angelia at 10sexyapples.com>wrote:
>> I'm running a pre_get_posts filter on is_author() in order to include my
>> custom post types when author.php is called.
>>
>> If I don't include nav_menu_item in the query set, the primary menu (
>> basically the default twenty ten nav ) disappears. This makes sense.
>>
>> But, if I DO include nav_menu_item in the query set, I get nav_menu_item/s
>> listed in the loop.
>>
>> add_filter( 'pre_get_posts', 'custom_posts' );
>>
>> function custom_posts( $query ) {
>>
>>    if ( is_author() )
>>        $query->set( 'post_type', array( 'post', 'nav_menu_item', 'lesson',
>> 'howto', 'workshop', 'attachment' ) );
>>
>>    return $query;
>> }
>
> This is one of the dangers/pitfalls of using pre_get_posts. It seems to be
> recommended often for some reason when dealing with custom post types, but
> it is much better to modify the request itself, versus any old get_posts or
> WP_Query call.
>
> The correct filter here would be either 'request' (direct QV access) or
> parse_request (whole WP object to play with).

That should work for this scenario, but the hooks in the WP class
(parse_request, request, etc.) only affect the main loop (mostly).  If
you want your plugin to be more invasive than that (widgets,
sub-loops, additional loops, etc.), pre_get_posts is the way to go.

If you want to use pre_get_posts in this case, you have to check two things:
1. is_author() -- are we on an author archive page?
2. $query->is_author -- is this query an author query, or some other
query on that page?

In conclusion, don't knock pre_get_posts :)  It's a perfectly cromulent hook.

Mike
--mdawaffe


More information about the wp-hackers mailing list