Inserting random posts

Combining two different custom post types in one single query, and still being able to control the number of each type of posts to be displayed can be a little tricky. If one single query is used with post_type = array( ‘type1’, ‘type2’…. ), you have to set posts_per_page to a considerably high number. Which is, i feel, dirty and bad 🙂

So you can use two different wp_query and can individually control the number of posts displayed for each type. But then the results from individual queries have to be ‘merged’ and displayed together, rather than one after the other. So then comes the need to use object buffering, which again, i’ve heard, is bad !! 🙂

So, anyway here’s code using second approach :

<?php 
$output = array();

//first query to retrieve cpt core-value
$cv_query = new WP_Query( 
    array( 
        'post_type' => 'core-value',
        //'posts_per_page'  => -1, this is a bad approach, you sure you want to display ALL core-values ?
    )
);
if( $cv_query->have_posts() ):
    while ( $cv_query->have_posts() ) : $cv_query->the_post(); 
    ob_start();
        ?>
        <div id='post-<?php the_ID();?>' <?php post_class( 'slider' );?> >
            <?php the_title();?>
            <?php the_post_thumbnail();?>
            <?php 
            /* and all other details of the post you want */
            ?>
        </div>
        <?php 
    $output[] = ob_get_contents();
    ob_end_clean();
    endwhile;
endif;
wp_reset_postdata();

//another wp_query to retrieve cpt events
$event_query = new WP_Query( 
    array( 
        'post_type'         => 'event',
        'posts_per_page'    => 3
    )
);
if( $event_query->have_posts() ):
    while ( $event_query->have_posts() ) : $event_query->the_post(); 
    ob_start();
        ?>
        <div id='post-<?php the_ID();?>' <?php post_class( 'slider' );?> >
            <?php the_title();?>
            <?php the_post_thumbnail();?>
            <?php 
            /* and all other details of the post you want */
            ?>
        </div>
        <?php 
    $output[] = ob_get_contents();
    ob_end_clean();
    endwhile;
endif;
wp_reset_postdata();

if( $output ){
    //shuffle the array to randomize it
    shuffle($output);

    //now finally echo them
    foreach ($output as $postdata) {
        echo $postdata;
    }
}
?>