How I can assign a different css class to each post of the 10 posts of each blog page?

Like this :

<li class="first-post">..
<li class="second-post">..
<li class="tenth-post">
Second page
<li class="first-post">..
<li class="second-post">..

So on ! Thank You a lot for the help.


Use the function post_class() in your template:

<div <?php post_class(); ?>>
// your post content

Then add a counter to the post classes per filter on post_class:

// functions.php
add_filter( 'post_class', function( Array $classes ) {

    static $number = 1;

    $classes[] = 'post-number-' . $number++;

    // reset the number
    if ( 11 === $number )
        $number = 1;

    return $classes;

You get a new class on each entry now that looks like post-number-1, post-number-2 and so on.

  • Thanks for your answer. but I want to make only 10 classes that they repeat. is there anyway to edit your function to make it happens. – dzdesigner May 25 '14 at 11:08
  • @user3358086 See my update. – fuxia May 25 '14 at 11:11

A simple counter can also do this:

<?php $counter = 1; ?>
<?php //wp loop start ?>
<div class="css-class-<?php echo $counter ?>">
<?php $counter++; ?>
<?php //end wp loop ?>

If you want to use better css class naming, you can use an array:

<?php $class_name = array ( 'first-post', 'second-post', ........, 'tenth-post' );
$arrKey = 0; ?>
<?php //wp loop start ?>
<div class="css-class-<?php echo $class_name[$arrKey] ?>">
<?php $arrKey++; ?>
<?php //end wp loop ?>
  • Thank you @The sufi for this amazing code, I will try all. Thanks to everyone – dzdesigner May 25 '14 at 11:53

As what @toscho said, is perfect. You can also differentiate each of the blog post with their post ID like this:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

There would be #post-1 for the post where the post id is 1, and so on...

  • Thanks, it doesnt work because I want to give only 10 css classes that they repeat.. which means I costumize only 10 css in my style.css – dzdesigner May 25 '14 at 11:10

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.