First x post with another template then the others

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x