PHP从WHILE循环显示3个列块

时间:2012-11-06 10:21:54

标签: php wordpress

我正在尝试建立一个模仿新www.digg.com网站布局的网站(博客)。

它包括一个顶部特征的全宽度柱子和下面,柱子在3列宽的块中。 blocka all设置为一定宽度并且Float left。

我正在构建的不同之处在于,只有顶部帖子是一个特色的全宽贴,任何一行都可以显示一个特色帖子,它应该扩展页面的整个宽度并向下推动其他块。 / p>

问题是,如果一个帖子被指定为特色并且它不在左栏中,那么它看起来就不对了。下图说明了如果特色帖子在第2或第3列中会发生什么。

遍历Wordpress帖子的WHILE循环,我计算并为每个帖子CSS类分配1到3之间的数字。示例<div class="col-1"> <div class="col-2"> <div class="col-3">

col-1 =左列帖子
col-2 =中柱柱
col-3 =右栏专栏

有时,帖子也会有一个名为featured的CSS类。当帖子被指定为featured时,它将扩展3列的全宽而不是仅1列。

只要featured帖子是结果集中的第一个帖子,这一切都很容易。但是,在下图中我已经显示了我的问题所在。如果我为每个帖子分配一个类别列名称1-3,为特色帖子分配一个特色类名称,那么假设我正在迭代该集合并将featured CSS类分配给通常具有的帖子类名col-2col-3然后出现问题。

下图显示了问题。在第3行,您可以看到如果我将特色类分配到第3行中心列(col-2)会发生什么

enter image description here

我需要以某种方式将类名col-1 col-2 col-3featured分配给while循环中的所有帖子,并确保featured帖子总是在第1列位置。

我愿意接受有关如何实现这一目标的任何建议或帮助吗?

下面是PHP循环的示例代码...(注意:我没有添加代码来检查精选帖子)

<?php
// Start our column count at 1
$column = 1;
while (have_posts()) : the_post();
    $col_class = 'post-col-' .$column;
?>

  <article <?php post_class($col_class); ?>>
      post content
  </article>

<?php
// Increase the Column count
$column++;
// After count has displayed 3, we reset the count
if($column == 4){
    $column = 1;
}
endwhile;
?>

1 个答案:

答案 0 :(得分:1)

只是想到你也可以“抓住”一个元素,直到整行被填满。如果您的帖子排序如下:

  1. 列表项
  2. 列表项
  3. 列表项
  4. 列表项
  5. 特色列表项
  6. 列表项
  7. 列表项
  8. 您可以像处理它们一样循环浏览它们,并在检测到特色项目时暂时存储它并在完成后显示它。如下所示:

    <?php
    $column = 1;
    $featured_list = array();
    while (have_posts()) : the_post();
      $col_class = 'post-col-' .$column;
    
      if(!$isfeatured) {
        echo '<article '.post_class($col_class).'>post content</article>';
      } else {
        $featured_list[] = '<article '.post_class($col_class).'>post content</article>';
      }
    
      // Increase the Column count
      $column++;
      // After count has displayed 3, we reset the count
      if($column == 4){
        $column = 1;
      // Print everything in the array, doing nothing if empty
      foreach ($featured_list as $featured_item) { 
        echo $featured_item;
      }
      // Reset the array
      $featured_list = array(); 
    }
    endwhile;
    ?>