Kanan tuteja
Kanan tuteja

Reputation: 135

How to add css class on every third post in wordpress?

I want to add a css class to every third post display on page. I have tried this code given below:

 <?php if (have_posts()) : ?>
 <?php $c = 0;
     while (have_posts()) : the_post(); $c++;
        if( $c == 3) {
            $style = 'third';
            $c = 0;
        }
        else $style='';
     ?>
     <div <?php post_class($style) ?> id="post-<?php the_ID(); ?>">

Upvotes: 1

Views: 1831

Answers (3)

immayankmodi
immayankmodi

Reputation: 8600

You do not need to change in any .php file or function. You can achieve this simply via CSS only.

#content div:nth-child(3n)
{
    background-color: yellow; 
}

NOTE: Simply change the #content div with your post div or class selectors, that's it, you are all set!

Here is the Demo: jsFiddle

Hope it helps!

Upvotes: 1

Ram Sharma
Ram Sharma

Reputation: 8819

try to change

 while (have_posts()) : the_post(); $c++;
 if( $c == 3) {
        $style = 'third';
        $c = 0;
    }
    else $style='';

with

 while (have_posts()) : the_post();
      if( $c % 3 == 0 )
         $style = 'third';
       else
         $style = '';

and make increment of varible $c++; before the while loop ends

I feel

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

is working, if not than change it to

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

Upvotes: 1

Devin
Devin

Reputation: 7720

I got this from somewhere, don't remember where, so it's not mine, but I've used it and works like a charm because it works on any page, archive, etc:

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

However, assuming you're using the default .post class, then you could easily target via CSS

.post:nth-child(3){your code}

or whatever class your post uses

Upvotes: 3

Related Questions