0

I have this code so far, which adds the classes first, second, and third to every first, second and third post in the loop. It also adds a class to the first 3 posts in the loop. But how can I make it so that it adds another class to the final 3 posts?

if (have_posts()) : 
while (have_posts()) : 
    the_post();
    $classes = array('themeview');
    $classes[] = $style_classes[$counter % 3];
    if ($counter < 3) $classes[] = 'top';
    $class = sprintf('class="%s"', implode(' ', $classes));
    $counter++
?>
<li <?php echo $class?>>

Thanks!

2

WP_Query seems to set two variables, $posts and $post_count when running(according to the source over at http://core.trac.wordpress.org/browser/tags/3.2.1/wp-includes/query.php ). You can access these two and work something out to figure out if you're in the last three posts.

var_dump those two to see if there's a count, add in your own counter and you should be good to go.

Edit: it's actually $post_count and $current_post that will be useful to you.

  • Thanks, that worked! Ended up need to use WP_Query for pagination reasons. – Mark Nov 2 '11 at 10:46
1

The Loop doesn't know how many records it's going to pull up, so you won't be able to tag your last three posts using the method you describe.

Actually, depending on what you want to do, that may not be true. If you are only concerned with the last three posts displayed on your home page, the total number of posts displayed on any archive or post page is controlled in the Admin back end using Settings > Reading > "Blog pages show at most...". That number is available using get_option( 'posts_per_page' ). Given that, you can add another if clause along the lines of if ( $counter > ( get_option( 'posts_per_page' ) - 3 )

Okay, other than that, you need to roll your own loop probably using get_posts(). With $posts_array = get_posts() you can then do if ( $counter > count( $posts_array ) - 3 ).

  • get_posts() combined with the counter line you provided worked perfectly, thanks! – Mark Oct 30 '11 at 6:12
  • @Mark If your problem has been solved than please mark Tom's answer as accepted. See FAQ for more info. Thanks and welcome aboard! – Michal Mau Oct 30 '11 at 12:13

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.