WordPress.org

Ready to get started?Download WordPress

Forums

Last Post in The Loop (6 posts)

  1. dtsn
    Member
    Posted 6 years ago #

    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.

  2. bigrodey77
    Member
    Posted 5 years ago #

    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;
    ?>
  3. bigrodey77
    Member
    Posted 5 years ago #

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

  4. simonsharks
    Member
    Posted 5 years ago #

    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
    ?>
  5. pepelsbey
    Member
    Posted 5 years ago #

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

  6. paulclaytonsmith
    Member
    Posted 5 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags