Reputation: 135
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
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
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
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