Display posts in random post types

There is no easy query that will do that (see below). You will need to process your results in PHP to get the sort you are looking for. Something like this:

$args = array(
  'posts_per_page'   => 5,    
  'orderby'          => 'post_date',
  'order'            => 'DESC',   
  'post_type'        => array('post', 'book'),  
  'post_status'      => 'publish'
); 
$posts = get_posts( $args );

$even = $odd = array();
$ei = 0;
$oi = 1;
foreach ($posts as $p) {
  if ('post' == $p->post_type) {
    $odd[$oi] = $p;
    $oi = $oi + 2;
  } elseif ('book' == $p->post_type) {
    $even[$ei] = $p;
    $ei = $ei + 2;
  }
}
$posts = $odd + $even;
ksort($posts);
foreach($posts as $post) {     
  echo $post->post_title.$post->post_type;
  echo '<br>';
}

Obviously, I used post types that exist on my dev server, but swapping those out is trivial. The idea is the same.

The only way I know to make sure you get equal numbers of each post type in the query would be to create a UNION. I don’t have the time write that now but option 4 from this answer should get you started.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)