Question

I need the first post that was ever posted to be styled differently. Is there a way that I can see if the post is first, and then change its contents? I currently have a div in all my posts. This needs to be replaced with different div.

Apparently the following piece of code can help, but I'm not sure how to implemenet it:

<?php if (have_posts()) : $postCount = 1; while (have_posts()) : $postCount++; ?>

I'm new with WordPress so not entirely sure how this could work?

Was it helpful?

Solution

Append following codes after yours:

<?php if (have_posts()) : $postCount = 1; while (have_posts()) : $postCount++; ?>

<?php if($postCount == 2) { ?>
  // SOMETHING TO DO WITH FIRST POST
<?php } else { ?>
  // SOMETHING TO DO WITH ALL OTHER POSTS
<?php } ?>

OTHER TIPS

<?php if (have_posts()) : $postCount = 0; while (have_posts()) : $postCount++; ?>

The above piece of code will create a $postCount variable and increment it every time The Loop loops. Note that I've changed it to start at 0 instead of 1.

We now have the post count in $postCount variable. We just need to find the first post and apply the styles to that post.

Normally, you'll have something like this:

<div class="post" id="post-<?php the_ID(); ?>">

Change that to:

<div <?php if($postCount == 1) { ?>class="YourSpecialClass"<?php } 
else { ?>class="post"<?php } ?> id="post-<?php the_ID(); ?>">

The above code will check if the $postCount is 1 (first post), and then add the class="YourSpecialClass" part as its <div> attribute.

A better readable version:

<?php if($postCount == 1) { ?>

    //the first post -- style it

<?php } else { ?>

    //other posts -- proceed normally

<?php } ?>

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top