php - WordPress循环: Wrap 3 search results in a row

标签 php wordpress twitter-bootstrap

我已将模板设置为在 col-4 中输出搜索条目以形成 3 列布局,并且我需要将每组 3 列包装成一行。

我已经想出了下面的内容,但我的打开和关闭 PHP 似乎是错误的,因为我目前在它自己的行中获取每个 1 个搜索条目。预先感谢您的帮助

<?php 
if ($counter % 3 == 0) { 
  echo '<div class="row">';
} ?>


<article id="post-<?php the_ID(); ?>" class="search-result col-md-4">
    <?php
    $entry_thumbnail = racks_entry_thumbnail();
    $entry_class = $entry_thumbnail ? 'search-thumbnail' : 'col-sm-4 col-md-4';
    ?>
        <?php if( $entry_thumbnail ) : ?>
            <div class=" <?php echo esc_attr( $entry_class ); ?>">
                <?php echo $entry_thumbnail; ?>

            <header class="entry-header clearfix">
                <h2 class="entry-title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title() ?></a></h2>
                </header>

        <div class="entry-summary">
          <?php the_excerpt(); ?>
        </div>

        <footer class="entry-footer">
          <a class="read-more" href="<?php the_permalink() ?>"><?php _e( 'Read more', 'racks' ) ?></a>
        </footer>

    </div>
        <?php endif;?>
    <div class="clearfix"></div>
</article><!-- #post-## -->

<?php $counter++ ; echo '</div>'; ?>

最佳答案

别忘了你只需关闭 </div>对于 $counter 能被 3 整除的情况:

<?php 
  echo ($counter % 3 === 0) ? '</div>' : '';
  $counter++;
?>

就目前情况而言,您关闭 </div>在循环的每一步。另请注意,您可能希望在迭代开始时进行此检查,并将其结果分配给变量。例如:

<?php

$counter = 0;
while ($counter < someLimit):
  $newRow = $counter % 3 === 0;

?>

  // at the beginning of template:
  <?= $newRow ? '<div class="row">' : ''; ?>

  // output goes here

  // at the end of template:
  <?= $newRow ? '</div>' : ''; ?>

<?php endwhile; ?>

另一种方法是使用输出缓冲区来存储某个数组中每个元素的输出,将该数组拆分为 block (使用 array_chunk() ),然后输出这些 block (将每个 block 包装在 <div class="row"></div> 结构中)。

关于php - WordPress循环: Wrap 3 search results in a row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453999/

相关文章:

php - 如何在表单提交时创建cookie?

php - Apple 推送服务器不工作,由单个 token 引起

WordPress 导航菜单顺序错误 - 如何修复?

javascript - jQuery 插件中没有冲突是如何工作的

javascript - 链接两个不同形式的单选按钮

用于创建动态行并插入数据库的php代码

php - 使用 laravel 更新表格

wordpress - WP REST API 如何检查 header 基本身份验证

javascript - Google map 未在使用 Avada 主题的实时网站上显示

html - 使用 Bootstrap 网格时可以省略容器元素吗?