I am developing a WordPress theme and want to determine if I am at the last post of the current loop page.

<?php get_header(); ?>
    <main id="main">
      <!-- =======  Blog Grid ======= -->
      <section class="news-grid grid">
      <div class="container">
    <?php if (have_posts()) : ?> 
    <?php $counter= 0 ?>
    <?php  while (have_posts()) : the_post(); ?>
            <?php if ($counter==0): ?>
              <div class="row">
            <?php endif; ?>
            <?php $counter++; ?>
                  <?php the_content(); ?>
          <?php if ($counter==3 || get_previous_post() == ""  /* or its the last post this loop page */  ): ?>
            </div>  <!-- close row -->
            <?php $counter=0; ?>
          <?php endif; ?>
     <?php  endwhile; endif; ?>
        </section><!-- End Blog Grid-->
    </main><!-- End #main -->
    get_footer(); ?>
  • You don't need the counter, just put an extra </div> after the loop, it will always come after the last post. Otherwise your logic is back to front, get_previous_post would only be empty if you were on the first post. Also have you considered using CSS grid instead of using divs to build rows? By using <div class="row"> you've trapped yourself into 3 posts per row and can't switch to 2 on smaller breakpoints, or 4 on larger screens
    – Tom J Nowell
    Jan 2 at 11:25
  • generally, $wp_query->post_count should give you the amount of posts in the loop; and $wp_query->current_post gives you the number of the current post, starting with zero for the first post. you can build you conditional based on those values.
    – Michael
    Jan 2 at 21:01
  • Thank you it worked for me. I did this $counter==$GLOBALS['wp_query']->post_count ) Jan 3 at 7:45

Your Answer

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

Browse other questions tagged or ask your own question.