[wp-hackers] pre_get_posts problem

Mike Schinkel mikeschinkel at newclarity.net
Sun Aug 1 23:13:00 UTC 2010


On Jul 31, 2010, at 2:42 AM, Angelia Baladon wrote:

> Hi all,
> Well, I'm still at it trying to figure out what to do to get my custom post
> types in the loop for my author.php file. Ironically, I think I'm beginning
> to understand why everyone is using the pre_get_posts solution ... ? I got
> this bit from Andrew ... thanks Andrew! but, unfortunately, I tested it and
> it didn't return any results. Does anyone else have anything to add that
> might help here? There are literally hundreds of sites out there
> recommending the pre_get_posts solution to this, so, it anyone can help sort
> this out, I'll be sure to go viral with the answer ... if only *sigh*. It's
> over my head, so, all I can do is keep begging ;-)
> 
> Here's the code from Andrew:
> 
> <code>
> function my_request_cpt_author( $query_vars ) {
>   if ( is_author() )
>      $query_vars['post_type'] = array( 'post', 'my_post_type' );
>   return $query_vars;
> }
> add_filter( 'request', 'my_request_cpt_author' );
> </code>

Both the problem you are having and with that solution are several fold.  First you are testing for is_author() which returns true if you are on an author page however it will return true for the query of nav_menu_items as well.  So you have to ensure you are not running an author query and not an nav_menu_item query.

Also the "request" hook is the one I thought of first too, but it is fired before the $query->is_author property has been set so it won't return true inside a request hook even if you are on an author page.

So you need to use the right hook (one that works is "parse_query") and you need to figure out if you are running an author query, not that you are just on an author page.  You can do that by checking for isset($query->query['author_name']).  Of course if something else sets "author_name" for another query on the author page this will fail, but you can cross that bridge when you come to it.

I know you also wanted to have it work for the search page so do the same with the "s" arg, i.e. test isset($q['s']).  Same caveats here too; if someone sets the "s" query_var in the other query on the search page you'll get unexpected results.

Try this and let me know if it solves your problem:

add_filter( 'parse_query', 'my_parse_query' );
function my_parse_query( $query ) {
	$q = $query->query;
	$is_menu = (isset($q['post_type']) && $q['post_type']=='nav_menu_item');
	if (!$is_menu && ((is_author() && isset($q['author_name']) || (is_search() && isset($q['s']))))) {
		$query->query_vars['post_type'] = array( 'post', 'nav_menu_item', 'lesson', 'howto', 'workshop', 'attachment' );
	}
}


-Mike


More information about the wp-hackers mailing list