Limit the post for differents custom post type in the same wp_query

I hate writing “you can’t do that” answers, but you can’t. That is the strict answer to your question about whether you can do this with a single WP_Query. You can’t limit post type counts individually in the same query using WP_Query (You are actually using query_posts. Please don’t. It is not the right tool for secondary loops.)

Even in raw SQL you have to write separate queries and UNION them together, which is how I’d approach this.

$sql = "(SELECT ID FROM {$wpdb->posts} WHERE post_type="books" AND post_status="publish" LIMIT 3)
UNION ALL
(SELECT ID FROM {$wpdb->posts} WHERE post_type="magazines" AND post_status="publish" LIMIT 2)
UNION ALL
(SELECT ID FROM {$wpdb->posts} WHERE post_type="videos" AND post_status="publish" LIMIT 1)";
// be sure to add any other conditions you need
$ids = $wpdb->get_col($sql);

Then run those $ids through a new WP_Query to get the post objects you need for a proper Loop.

You could even break the SQL into a pattern and reuse it. Something like…

$sqlpat = "(SELECT ID FROM {$wpdb->posts} WHERE post_type="%s" AND post_status="publish" LIMIT %d)";
$sql="(".sprintf($sqlpat,'books',3).') UNION ALL ('.sprintf($sqlpat,'magazines',2).') UNION ALL ('.sprintf($sqlpat,'videos',1).')';

Assuming I didn’t make a mistake (the code is not tested), you should then have what you want– three post types each with a particular count. They may not come out in the order you want so you may have to sort them in PHP, or build an even trickier SQL query.

Leave a Comment