WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Identify the first and last posts on the page (7 posts)

  1. vagrantmonkey84
    Member
    Posted 4 years ago #

    What conditional tags do I need to identify the first and last posts on the page so that I can format them differently? I have hunted through the help docs but I have not found those yet.

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    There aren't any specific conditionals for the first and last posts on a page. You should be able to identify the first post by using something like:

    <?php $c = 0; $style='';
    if (have_posts()) : while (have_posts()) : the_post();
    $c++;
    if( $c == 1 ) $style='first';
    elseif( $c == get_option( 'posts_per_page' ) ) $style='last';?>
    <div <?php post_class($style);?> id="post-<?php the_ID();?>">

    which should apply the class .first to the first post only and the class .last to the last post on each page.

  3. vtxyzzy
    Member
    Posted 4 years ago #

    @esmi: Will that work for the last page if there are fewer than posts_per_page on the page?

  4. esmi
    Forum Moderator
    Posted 4 years ago #

    No - it picks up the last post number via the "posts per page" option in Admin/Settings/Reading.

  5. vtxyzzy
    Member
    Posted 4 years ago #

    This is TOTALLY UNTESTED, but it might work on short pages:

    <?php $c = 0; $style='';
    if (have_posts()) : while (have_posts()) : the_post();
      $c++;
      if( $c == 1 ) {
        $style='first';
      } elseif ( $c == $wp_query->post_count ) ) {
        $style='last';?>
      }
      <div <?php post_class($style);?> id="post-<?php the_ID();?>">
  6. vagrantmonkey84
    Member
    Posted 4 years ago #

    Thanks all! I ended up using the count script to get the first post and I found a way to move my end-style out of the lop so it caps of the last post nicely. I am a bit curious to try the code suggested by vtxyzzy though... it seems like that ought to do the trick. Thanks again!

  7. chris.op
    Member
    Posted 3 years ago #

    Correct a few mistakes in vtxyzzy's post

    <?php $c = 0; $style=''; if (have_posts()) : while (have_posts()) : the_post(); $c++; if( $c == 1 ) { $style='first'; } elseif ( $c == $wp_query->post_count ) { $style='last'; } ?>
      <div <?php post_class($style);?> id="post-<?php the_ID();?>">

    Thanks

Topic Closed

This topic has been closed to new replies.

About this Topic