我正在构建一个wordpress页面(基于quark,使用ACF),使用foreach(get_field('exhibitions') as $post_object)
我希望'col grid_3_of_12-divs'包含来自其他帖子的信息以div分组,每个div中有四个。与此问题的作者类似的问题包括:Is there an easy way to do 4 at a time in a php foreach loop
我已经尝试过使用array_chunk,但似乎无法在不弄乱其他帖子检索信息的情况下使用它。
有人可以帮我这个吗?
我是一名自学成才的php初学者,所以如果我的代码很蠢,请原谅。
<?php get_header(); ?>
<div id="primary" class="site-content row clearfix" role="main">
<div class="col grid_12_of_12">
<?php while ( have_posts() ) : the_post(); ?>
<?php foreach(get_field('exhibitions') as $post_object): ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<div class="col grid_3_of_12">
<h3 class="exhibition title"> <?php echo $post_object->short_title?> </h3>
<?php $attachment_id = $post_object->thumbnail;
$image_attributes = wp_get_attachment_image_src( $attachment_id, 'full' ); ?>
<img src="<?php echo $image_attributes[0]; ?>">
<p class="exhibition short desc"> <?php echo $post_object->short_description?> </p>
</div>
</a>
<?php endforeach; ?>
<?php content_nav( 'nav-below' ); ?>
<?php endwhile; ?>
</div>
</div>
答案 0 :(得分:3)
添加一个计数器。然后当计数器位于正确位置时,添加一个关闭或打开div。
<?php get_header(); ?>
<div id="primary" class="site-content row clearfix" role="main">
<div class="col grid_12_of_12">
<?php while ( have_posts() ) : the_post(); ?>
<?php $counter = 0; /* ADD THIS */ ?>
<?php foreach(get_field('exhibitions') as $post_object): ?>
<?php if ($counter % 4 == 0): /* ADD THIS */ ?>
<div class="group-of-4-posts-wrapper">
<?php endif; ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<div class="col grid_3_of_12">
<h3 class="exhibition title"> <?php echo $post_object->short_title?> </h3>
<?php $attachment_id = $post_object->thumbnail;
$image_attributes = wp_get_attachment_image_src( $attachment_id, 'full' ); ?>
<img src="<?php echo $image_attributes[0]; ?>">
<p class="exhibition short desc"> <?php echo $post_object->short_description?> </p>
</div>
</a>
<?php if ($counter % 4 == 3): /* ADD THIS */ ?>
</div>
<?php endif; ?>
<?php $counter++ ?>
<?php endforeach; ?>
<?php
// this closes the div if there is not a number of posts that is evenly
// divisable by 4, like 11 posts. with 11 posts, the last post would have
// ($counter % 4 == 3) equal to false, because $counter % 4 would = 2
// adding this, closes the div, if it was not already closed
if ($counter % 4 != 0): /* ADD THIS. */
?>
</div>
<?php endif; ?>
<?php content_nav( 'nav-below' ); ?>
<?php endwhile; ?>
</div>
</div>