Wordpress post循环添加类


Wordpress post loop adding class

我正在使用Wordpress标签在我的网站上构建特色帖子部分(主页上显示了3个标记为"特色"的最新帖子),使用以下代码:

                        <?php
                            $args=array(
                              'tag' => 'featured',
                              'showposts'=>3,
                              'caller_get_posts'=>1
                            );
                            $my_query = new WP_Query($args);
                            if( $my_query->have_posts() ) {
                              while ($my_query->have_posts()) : $my_query->the_post(); ?>
                              <div class="featured-article">
                                <!--thumbnail, title and link code here -->
                              </div>
                               <?php
                              endwhile;
                            } //if ($my_query)
                          wp_reset_query();  // Restore global post data stomped by the_post().
                        ?>

每个条目都用"特色文章"包装,但由于我希望第一个帖子是全宽的,另两个是半宽的,我想知道如何为它们添加合适的类?所以,第一个帖子得到了"全宽"类和另外两个"半宽"类。。。

如果我没有正确解释(英语不是第一语言),我深表歉意。

如有任何帮助,将不胜感激

在循环中,您可以使用$my_query->current_post获取帖子的索引。

$class = $my_query->current_post == 0 ? 'full-width' : 'half-width';

您可能还想确保该类只应用于第一页的第一项

$class = $my_query->current_post == 0 && !is_paged() ? 'full-width' : 'half-width';

这是你的环路

 <?php
 $args=array(
     'tag' => 'featured',
     'showposts'=>3,
     'caller_get_posts'=>1
 );
 $my_query = new WP_Query($args);

 if( $my_query->have_posts() ) {
     while ($my_query->have_posts()) : $my_query->the_post();
     $class = $my_query->current_post == 0 && !is_paged() ? 'full-width' : 'half-width'; ?>
         <div class="featured-article <?php echo $class; ?>">
         </div>
     <?php
     endwhile;
 } //if ($my_query)
 wp_reset_query();  // Restore global post data stomped by the_post().
 ?>

您可以使用计数器来解决此问题。

<?php
       $args=array(
         'tag' => 'featured',
         'showposts'=>3,
         'caller_get_posts'=>1
      );
      $my_query = new WP_Query($args);
      //add classes
      $counter = 0;
      $classes = '';
      if( $my_query->have_posts() ) {
          while ($my_query->have_posts()) : $my_query->the_post(); 
              $classes = $counter == 0 ? ' full-width' : ' half'; 
 ?> 
       <div class="featured-article<?php echo $classes; ?>">
           <!--thumbnail, title and link code here -->
       </div>
 <?php
              $counter++;
           endwhile;
      } //if ($my_query)
      wp_reset_query();  // Restore global post data stomped by the_post().
  ?>

或者,您可以为添加类创建一个自定义文件。