如何在wordpress的每三个帖子上添加css类?

问题描述:

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

我想在页面上的每三个帖子显示中添加一个css类。 我试过下面给出的代码: p>

 &lt;?php if(have_posts()):?&gt; 
&lt;?php $ c = 0; 
 while  (have_posts()):the_post();  $ c ++; 
 if($ c == 3){
 $ style ='third'; 
 $ c = 0; 
} 
 else $ style =''; 
?&gt; 
&lt;  ; div&lt;?php post_class($ style)?&gt;  id =“post-&lt;?php the_ID();?&gt;”&gt; 
  code>  pre> 
  div>

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

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

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!