1

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(); ?>">
2

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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(); ?>">

Comments

1

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!

3 Comments

Change the CSS selectors that i already mentioned in my answer and also the style you want to give to every 3rd element. This is only an example that you can simply use. Please prepare your jsfiddle or update your answer with some html code, i'll check your example code.
please find the sample div. <div>div 1 <div> test</div><div>test2</div></div>
Select divs that are direct children of #content like this: #content>div:nth-child(3n). If they are children of children, you can do this: #content>div>div:nth-child(3n).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.