WordPress Development Asked by timmyg on December 31, 2021
I want to loop my posts into a 2 column grid, but if there is an odd number of posts, there is an empty space on the even side of the grid.
How could I get an image to appear in this empty space only if there are an odd number of posts? So it would be:
Post 1 | Post 2
Post 3 | img
I tried using the code here, but not sure how to apply the Modulo
Operator because the image should appear after the loop, no?
If my code is super basic like:
<div class="small-12 large-6 columns end">
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
Post title, thumbnail, excerpt, etc
<?php endwhile; endif; ?>
</div>
Using the built-in current_post you can easily separate the odd and even post.
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 4,
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ):
while ( $loop->have_posts() ) : $loop->the_post();
if ( $loop->current_post % 2 == 0 ):
// Even
the_title();
else:
// Odd
the_title();
endif;
endwhile;
endif;
Answered by cryptex_vinci on December 31, 2021
The common mistake people make in this situation is they start to introduce bunch of custom counters to keep track of state.
Really WP_Query
just has those already. In your case that would be global $wp_query
and $wp_query->post_count
and $wp_query->current_post
. That should be quite enough to figure out even/odd overall and current iteration in the loop.
Answered by Rarst on December 31, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP