I'm looking to create a site wide feed on my site and have multiple custom post types. I'd like to display say 3 posts from at least 3 different post types. I can get the latest 10 posts across each post type, and I can get the latest 10 overall, but I'd like to specify so that I only get 3 from each so things are even. Is the best way to do it do 3 different queries and then merge them? I get how to do this separately, but I want them all integrated and sorted by timestamp. Any suggestions?
This method uses a counter and 1 query. Only 3 posts from each post type can ever be displayed.
$args = array( 'post_type' => array( 'type1', 'type2', 'type3' ), 'posts_per_page' => -1 ); $myquery = new WP_Query( $args ); $type1 = 0; $type2 = 0; $type3 = 0; $count = 0; while ( $myquery->have_posts() ) : $myquery->the_post(); if ( $post->post_type == 'type1' ) $type1++; if ( $post->post_type == 'type1' && $type1 > 3 ) continue; if ( $post->post_type == 'type2' ) $type2++; if ( $post->post_type == 'type2' && $type2 > 3 ) continue; if ( $post->post_type == 'type3' ) $type3++; if ( $post->post_type == 'type3' && $type3 > 3 ) continue; $count++; if ( $count > 9 ) continue; // Do Stuff endwhile;
This might not be the best solution if you have a really large amount of posts because it will loop through all the posts and if the count is higher than 3 for the given post type it will go back to the beginning of the loop.