0

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>
1

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.

| improve this answer | |
1

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;
| improve this answer | |

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.