Wordpress循环Post计数器


Wordpress Loop Post Counter

这段代码为Wordpress循环中的每一个第一/第二/第三倍数添加一个唯一的类:

<?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>

第一个帖子有一个first类,第二个帖子有一个second类,第三个帖子有一个third类,然后它重置为第四个帖子有一个first类,第五个帖子有一个second类,等等。

是否有一种方法,也使只有前三个帖子有一个额外的类称为"特殊"?

你不应该把这么多代码压缩成一行。

相反,每行写一条语句,这样可以让你灵活地添加东西,比如你的特殊类:

<?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>

只需在代码中添加一个if语句,就像这样-

<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>