I am creating a theme for my site. I would like to display the last 5 articles on the home page but with a different display for the first articles.
So I created this code that I try to tweak but impossible to display the first article with the first template and the 4 others with the second template. I don’t know if it’s possible to do it the way I want to do it, but this way seems to be the easiest
My code :
<?php
$query = [
'post_type' => 'post',
'posts_per_page' => 5
];
$query = new WP_Query($query);
while ($query->have_posts()) : {
$query->the_post();
if($query === 1) :
get_template_part('loops/acc-cards');
else() :
get_template_part('loops/cards');
}
wp_reset_postdata();
?>
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
I haven’t tested this, but it looks like you just need to set an iteration variable (usually abbreviated $i), like this:
<?php
$i = 0; // This sets your variable
$query = [
'post_type' => 'post',
'posts_per_page' => 5
];
$query = new WP_Query($query);
while ($query->have_posts()) : {
$query->the_post();
if($i == 0) :
get_template_part('loops/acc-cards');
else() :
get_template_part('loops/cards');
}
$i++ // This iterates the iteration variable $i
wp_reset_postdata();
?>
Method 2
Solution found, it missed an endwhile;
<?php
$query = array(
'post_type' => 'post',
'posts_per_page' => 5
);
$query = new WP_Query($query);
while ($query->have_posts()) :
$query->the_post();
if($query->current_post === 0) :
get_template_part('mining-inc/loops/acc-cards');
else :
get_template_part('loops/cards');
endif;
endwhile;
wp_reset_postdata();
?>
Method 3
The proper day to do it in WordPress is to use the current_post value instead of setting your own variable like $i. current_post is the index of the current post in a loop that starts with 0.
<?php
$query = array(
'post_type' => 'post',
'posts_per_page' => 5
);
$query = new WP_Query($query);
while ($query->have_posts()) :
$query->the_post();
if($query->current_post === 0) :
get_template_part('loops/acc-cards');
else:
get_template_part('loops/cards');
endif;
endwhile;
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