1

I want to display posts from multiple post types (photo, post), with one post from "photo" post type and another post from "post", in the same loop. Can anyone help me? Here is my code:

<?php
$args = array(
    'post_type'=> array('photo', 'post'),
    'orderby' => 'date',
    'posts_per_page' => 10,
    'paged' => get_query_var('paged'),
);
$query=new WP_Query($args);

if ( $query->have_posts() ) while ( $query->have_posts() ) : $query->the_post(); global $post;
    $post_type=$post->post_type;
    if($post_type=='photo'){ ?>
        <li class="plist"><a href="<?php the_permalink(); ?>"> <h3><?php the_title(); ?></h3> </a> </li>
    <?php }  
    if($post_type=='post'){ ?>
        <li class="plist"><a href="<?php the_permalink(); ?>"> <h3><?php the_title(); ?></h3> </a> </li>
    <?php } 
endwhile;
?>
3
  • 3
    Welcome to WPSE. What did you try so far?
    – birgire
    Jul 1, 2014 at 14:52
  • Do you want to actually merge them? Or do you want to display post 1 from "posts", then post 1 from "photos", etc.? Answer please in an edit. Thanks.
    – kaiser
    Jul 1, 2014 at 15:06
  • Yes, I want to display post 1 from post and post 1 from photo. Again post 2 from from post and post 2 from photo and so on.. Jul 1, 2014 at 15:11

1 Answer 1

1

You would need two queries to achieve this. You can't specify the limit per post type in WP_Query (without modifying the raw SQL). What you could do is simply query the posts and the photos and merge the resulting arrays:

// Fetch posts
$posts_query = new WP_Query( array(
    'post_type'=> 'post',
    'orderby' => 'date',
    'posts_per_page' => 10,
    'paged' => get_query_var( 'paged' )
) );

// Fetch photos
$photos_query = new WP_Query( array(
    'post_type'=> 'photo',
    'orderby' => 'date',
    'posts_per_page' => 10,
    'paged' => get_query_var( 'paged' )
) );

// List of merged photos and posts
$mergedposts = array();

for ( $i = 0; $i < 10; $i++ ) {
    // Add post to list
    if ( isset( $posts_query->posts[ $i ] ) ) {
        $mergedposts[] = $posts_query->posts[ $i ];
    }

    // Add photo to list
    if ( isset( $photos_query->posts[ $i ] ) ) {
        $mergedposts[] = $photos_query->posts[ $i ];
    }
}

Then, you should set up the post data using setup_postdata (as you can't use the_post outside of the query scope).

0

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.