dongxi4235
2014-08-25 06:09
浏览 14
已采纳

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

图片转代码服务由CSDN问答提供 功能建议

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

 &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; 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhuzhou4504 2014-08-25 06:37
    已采纳

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

    点赞 打赏 评论
  • duandang2123 2014-08-25 06:33

    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

    点赞 打赏 评论
  • doulangdang9986 2014-08-25 06:44

    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!

    点赞 打赏 评论

相关推荐 更多相似问题