• Resolved vagrantmonkey84

    (@vagrantmonkey84)


    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.

Viewing 6 replies - 1 through 6 (of 6 total)
  • 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.

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

    No – it picks up the last post number via the “posts per page” option in Admin/Settings/Reading.

    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();?>">
    Thread Starter vagrantmonkey84

    (@vagrantmonkey84)

    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!

    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

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Identify the first and last posts on the page’ is closed to new replies.