开发者

Wordpress Loop Post Counter

This code adds a unique class to every first/second/third multiple in the Wordpress loop:

<?php
$style_classes = array('first','second','third');
$style_index = 0;

if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php $k = $style_index%3; echo "class=post&nbsp;$style_classes[$k]"; $style_index++; ?>>test</div>

So the first post has a class of first, the second a class of second, the third a class of third, and then it resets with the fourth post having a class of first, the fifth post a class of second, etc etc.

Is there a way to also make only the first three posts have an addition开发者_如何学Cal class called "special"?


You should not compress together so much code into one line.

Instead, make one statement per line, that keeps you flexible to add stuff, like your special class:

<?php
$style_classes = array('first','second','third');
$style_index = 0;

if (have_posts()) : 
    while (have_posts()) : 
        the_post();
        $style_index = $wp_query->current_post;
        $classes = array('post');
        $classes[] = $style_classes[$style_index % 3];
        if ($style_index < 3) $classes[] = 'special'
        $class = sprintf('class="%s"', implode(' ', $classes));
?>
<div <?php echo $class?>>test</div>


Just add one if statement to your code like this -

<div>
   <?php 
      $k = $style_index%3; 
      if ($style_index < 3) $special = "special";
      else $special = "";
      echo "class=post&nbsp;$style_classes[$k] $special"; 
      $style_index++; 
   ?>
test
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜