Wordpress - How to mark every 3rd post

My approach. No extra function, no filter. :)

<?php $GLOBALS['wpdb']->current_post = 0; ?>
<div <?php post_class( 0 === ++$GLOBALS['wpdb']->current_post % 3 ? 'third' : '' ); ?>>

Alternative:

<div <?php post_class( 0 === ++$GLOBALS['wpdb']->wpse_post_counter % 3 ? 'third' : '' ); ?>>

As an addition to @helgathevikings answer

Use the post_class() fn without polluting the global namespace

  1. Using static variables inside a class allows the same behavior as having global variables: They stay in place and don't change, unless you don't alter them.
  2. Even better (as @Milo suggested in the comments), take the current post from the DB class.
The Example:
function wpse44845_add_special_post_class( $classes )
{
    // Thanks to @Milo and @TomAuger for the heads-up in the comments
    0 === $GLOBALS['wpdb']->current_post %3 AND $classes[] = 'YOUR CLASS';

    return $classes;
}
add_filter( 'post_class','wpse44845_add_special_post_class' );

Update

We could utilize the current_post property of the global $wp_query object. Let's use an anonymous function, with the use keyword, to pass on the global $wp_query by reference (PHP 5.3+):

add_filter( 'post_class', function( $classes ) use ( &$wp_query )
{
    0 === $wp_query->current_post %3 AND $classes[] = 'YOUR CLASS';

    return $classes;
} );

Further on, we could restrict it to the main loop with a in_the_loop() conditional check.


if your theme uses post_class() to generate post classes you could try. i'm not 100% sure how it will handle pagination b/c i don't have enough posts on my local install to test it out

add_filter('post_class','wpa_44845');

global $current_count;

$current_count = 1;

 function wpa_44845( $classes ){

    global $current_count;

    if ($current_count %3 == 0 ) $classes[] = 'special-class';

    $current_count++;

    return $classes;

 }