我已将模板设置为在 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/