• How can i determine when i am at the last post of The Loop?

    I want to apply a specific class to the last post, but The Loop uses a while loop, and i can’t seem to find a way of getting any sort of count for the number of posts it’s outputting.

Viewing 5 replies - 1 through 5 (of 5 total)
  • I know it’s a little late but I thought this might help if someone else has this problem in the future…

    I could not find a native function to check to see if we were in the last post of the loop. My way around this was to set a constant equal to the amount of posts to display on a page (you set this value in the settings) and keep track of how many posts we have displayed. When we are in the last one, you do whatever special stuff you wanted to do. I also could not find a way an easy way to get this so I can to use a “magic number.”

    In my case, I wanted to display an <hr /> after each post, but not after the last post (it looked stupid with my template).

    <?php
    $postCount = 0;
    define(POSTS_PER_PAGE,3); //this example assumes i display 3 posts on the main page
    while (have_posts()):
    	the_post();
    	if (++$postCount !== POSTS_PER_PAGE):
    		// we're not at the last post, display it regularly
    	else:
    		// here is the last post, print it out with your special formatting
    	endif;
    endwhile;
    ?>

    I meant to edit my last post and ended up posting another. My bad.

    Rather than use bigrodey77 static variable, you can use the WordPress variable $posts_per_page. So to determine the first and last post you could use:

    <?php
    $postCount = 0;
    
    // Start of The Loop
    
    if (++$postCount == 1) {
         // FIRST POST
    } 
    
    if ($postCount == $posts_per_page) {
         // LAST POST
    }
    
    // End of The Loop
    ?>

    What if numbers of post smaller than $posts_per_page?
    How can i get the last post?

    For situation’s like pepelsbey’s, where the number of posts on the page might be less than $posts_per_page, you can check against the length of the $posts array rather than $posts_per_page:

    <?php
    $postCount = 0;
    
    // Start of The Loop
    
    if (++$postCount == 1) {
         // FIRST POST
    } 
    
    if ($postCount == sizeof($posts)) {
         // LAST POST IN LOOP
    }
    
    // End of The Loop
    ?>
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Last Post in The Loop’ is closed to new replies.