2013-12-22 27 views
0

我建立一个WordPress页面的工作(根据夸克,使用ACF)显示来自其他职位信息使用foreach(get_field('exhibitions') as $post_object)

我想要的“山坳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> 

回答

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> 
+0

不错的使用'%'(模数)运算符。 – JakeGould

+0

谢谢!它完美的工作! – user3126254

+0

我只是在寻找像这样的东西。你从我身上投了票,因为柜台里有11个帖子。 –