0

I want to output the 5 latest posts. But the template of the first 2 must be different than the other 3 posts. So I've created two queries.

The first one shows the 2 posts:

<?php
$loop = new WP_Query( array(
   'post_type' => 'Post',
   'posts_per_page' => 2
   )
);
?>

 <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

      <?php get_template_part('loop-templates/blog-item-big'); ?>

 <?php endwhile; wp_reset_query(); ?>

The other query must show the other posts (limited with 3 posts):

<?php
$loop = new WP_Query( array(
   'post_type' => 'Post',
   'offset' => 2,
   'post_per_page' => 3
   )
);
?>

 <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

      <?php get_template_part('loop-templates/blog-item-small'); ?>

 <?php endwhile; wp_reset_query(); ?>

The first loop seems to work perfectly. It only shows the 2 last added posts. The second loop seems to start after the second post because of the offset parameter. But it shows more than 3 posts.

What is wrong with that query?

2

It shows more than 3 posts because you used post_per_page when it should be posts_per_page (note the plural "posts").

But actually, you can use the same query and use a counter to display the different template parts:

$loop = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
) );

$c = 1; // post counter
while ( $loop->have_posts() ) : $loop->the_post();
    if ( $c < 3 ) : // the first and second posts
        get_template_part( 'loop-templates/blog-item-big' );
    else :
        get_template_part( 'loop-templates/blog-item-small' );
    endif;

    $c++;
endwhile;
/* Or a simpler loop..
$c = 1; // post counter
while ( $loop->have_posts() ) : $loop->the_post();
    $template = 'blog-item-' . ( $c < 3 ? 'big' : 'small' );
    get_template_part( 'loop-templates/' . $template );

    $c++;
endwhile;
*/

// not wp_reset_query()
wp_reset_postdata();
1
  • 1
    Yes that's it ! Thank you very much. I had to split it into two queries because I needed to wrap both loops completely different. – Dennis Jul 13 '20 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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