0

I want to loop through 3 custom post types + posts and display the latest post from each.

This is what I have so far. This only takes the four most recent posts but not one only from each post type. Many thanks in advance

<?php $args = array(
      'post_type' =>.  array('post','mixes','artists','releases'),
      'posts_per_page' => '4',
        );

query_posts( $args );
while ( have_posts() ) : the_post(); ?>

  do stuff here         

<?php   endwhile; ?> 
2
  • Welcome to WPSE. Just a point of note here, when adding code do a question/asnwer, keep the following in mind, when you have added code to the editor, highlight that code, and just above the editor is a {} sign, click on that sign. This will add your code in a codeblock, as you can see in my edit. BTW, don't use query_posts Commented May 28, 2014 at 9:19
  • Read this on why you shouldn't use query_posts: wordpress.stackexchange.com/a/1755/47733
    – kraftner
    Commented May 28, 2014 at 10:58

1 Answer 1

0

That way won't work as you have found out it will grab just the 4 posts from the loop.

To do this you need to do a search of each post type, something like below will work:

$terms = array('post', 'mixes', 'artists', 'releases');
  if ( !empty( $terms ) && !is_wp_error( $terms ) ){
   foreach ( $terms as $term ) {
    $my_query = new WP_Query('posts_per_page=1&post_type='.$term);
    while ($my_query->have_posts()) : $my_query->the_post();
     echo '<h2>'.$term.'</h2>';
     echo '<ul>';
      echo '<li>'.get_the_title().'</li>';
     echo '</ul>';
    endwhile; wp_reset_query();
   }
  }

That should do the following:

Post Type 1 - post title

Post Type 2 - post title

Post Type 3 - post title

Post Type 4 - post title

2
  • Hey Gareth, thanks so much! You code works perfectly. One quick question: Is there a way to add a custom page to this loop? Eg take 'mixes' out and put mixes_page.php in? Once again thanks again!
    – Rico Shaft
    Commented May 28, 2014 at 12:49
  • What does mixes_page.php do, the loop needs to reference the data so your best to sticking with grabbing the data from the post types. As my amswer solved your question, can you accept it as the answer (on arrows to left, there will be a tick below). Commented May 28, 2014 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.