0

I have a homepage on which I want to display the latest post different from the other posts. I haven't used post_class and I am not sure how to.

Would I be able to achieve what I want using post_class?

3 Answers 3

1

You should be using post_class (and body_class for that matter) but you don't need it for this. Alter your Loop on your home page to conditionally format the first post.

$first = (!is_paged()) ? true : false;
if (have_posts()) {
  while (have_posts()) {
    the_post();
    if ($first) {
      // code to format the first post
      $first = false;
    } else {
      // code to format all the other posts
    }
  }
}

If all you need is a small change that can be made via CSS then you can pass post_class a parameter.

$first = (!is_paged()) ? 'is_first' : 'not_first';
if (have_posts()) {
  while (have_posts()) {
    the_post();
    echo '<div ',post_class($first),'>';
      // the rest of your Loop
    echo '</div>';
    $first = 'not_first';
  }
}
4
  • post_class() echos it return value. You could use get_post_class() instead, but it comes with out the HTML tags class attribute.
    – kaiser
    May 5, 2013 at 16:27
  • 1
    @kaiser : Test the code. Note that that is a comma not a period. There is a peculiarity with echo. If you use a comma, strings are echoed immediately, not concatenated which means that works perfectly well.
    – s_ha_dum
    May 5, 2013 at 16:34
  • Oh, really? Didn't even know that. Thanks for the explanation.
    – kaiser
    May 5, 2013 at 16:35
  • @s_ha_dum that is exactly what i needed, thanks!. i have a custom design and i think its advance. where can i get more help material in customizing my layout?
    – Ammar
    May 5, 2013 at 22:38
1

It's actually very simple: Use the $wp_query object property current_post. You have to note that it's starting the index with 0, so I'm counting up by one in the example below.

if ( have_posts() )
{
    while( have_posts() )
    {
        the_post();
        ?>
        <article <?php post_class( "post-nr-{$GLOBALS['wp_query']->current_post+1}" ); ?>>
            <?php
            the_title();
            the_content();
            ?>
        </article>
        <?php
    }
}
0

I wouldn't use php code to do this. It adds "hits" that are not that necessary. CSS might be a better option for you e.g.

.post:nth-child(1) { ... }

or

.post:first-of-type { ... }

and let the browser do the heavy lifting of styling it up? Just a thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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