1

I'd like to only show the excerpt for the first post in my main query. I was wondering the best way to approach this.

What I have tried so far is:

  1. Making a custom homepage and using two queries, one that returns 1 post with an excerpt and another queries that returns posts without.
  2. Just using the default queries but using css to hide the excerpts for all posts but the first, using nth-child.

Both of these work well enough, but I was wondering if there was a better way to do this, through a function or filter.

Thanks!

3

You can use $wp_query->current_post in your loop to check the current post. You don't need two loops, one will do the trick If you need excerpt for first post only, you can do something like this. Just remember, the first post in the loop is 0, and not 1

if ( !$wp_query->current_post > 0 ) :
   the_excerpt();
else :
   <--- DO SOMETHING ELSE FOR OTHER POSTS
endif;

For all the WP_Post member variables, go and check the link provided from the codex

  • 1
    I prefer this method, but I must admit it can be rather verbose in some cases ;-) – birgire Jun 27 '14 at 9:48
  • This works quite well, but I wonder how to prevent it from showing the excerpt of the first posts on subsequent pages... – justinw Jun 29 '14 at 0:51
  • Are you using a custom query, because my code will only target post number one using the main query. If you are using a custom query and it looks something like $query = new WP_Query, change my code to $query->current_post > 0. If you are using query_posts you will have problems as well – Pieter Goosen Jun 29 '14 at 6:42
2

You can set it with a counter. Using the default loop as a sample:

<?php
  $firstExcerpt = 0; // Set the variable to 0 so we can check for it later.
  if ( have_posts() ) : while ( have_posts() ) : the_post();
?>

  <h2><?php the_title(); ?></h2>
  <?php
    if ($firstExcerpt < 1) { // Check if it's been displayed
      the_excerpt();
      $firstExcerpt++; // Changes the variable so that next time, it won't show
    };
  ?>

<?php endwhile; endif; ?>
  • Seems we raced each other to essentially the same answer. – Pat J Jun 27 '14 at 12:31
  • @Pat J Haha, pretty much! I think you got me beat though. – Arkuen Jun 28 '14 at 1:38
1

What about something simple like:

$i = 1;
if( have_posts() ) {
    while( have_posts() ) {
        the_post();
        if( 1 == $i ) {
            the_excerpt();
        }
       // the rest of your loop
       $i++;
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.