I have three custom post type:
- books
- magazine
- videos
Now i want to limit the number of post for custom post type, for example:
- books => 3 post
- magazine => 2 post
- videos => 1 post
I used a query post like this:
query_posts( array(
'post_type' => array(
'books',
'magazine',
'videos'
),
'paged' => $paged,
'posts_per_page' => 6,
));
$counter = 1;
if (have_posts()) :
while (have_posts()) : the_post();
if (($counter == 2) || ($counter == 3) || ($counter == 4)) {
$div = 'alpha';
} elseif(($counter == 6)) {
$div = 'omega';
} else {
$div = '';
}
The problems is i cant limit the numbers by custom post type.
Any idea?
Thank you 🙂
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 usingWP_Query
(You are actually usingquery_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.Then run those
$ids
through a newWP_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…
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.
You can do this by merging queries: