简体   繁体   中英

Break the loop into half, if the loop count is even

I want to break the loop into half of the total loop count. If the total loop count is odd, I would like to remove the last array item in order to make the total loop count even and add the deleted item to the second half.

Here is the code structure to demonstrate the loop-

<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>
<div class="row">
   <div class="col-lg-6">
      <!-- The first half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
   <div class="col-lg-6">
      <!-- The second half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
</div>

I don't know how to control the loop based on my mentioned conditions. That's why I couldn't able to try loop controlling.

In a single loop. Hopefully, it'll work. Couldn't test so let me if you face any situation.

<?php
$faqs = new WP_Query([
    'post_type' => 'faq',
    'post_status' => 'publish',
]);
$half = intval($faqs->post_count / 2);
$counter = 0;
?>
<div class="row">
    <div class="col-lg-6">
    <?php while ($faqs->have_posts()) : $faqs->the_post(); ?>
        <?php if ( $counter === $half ) : ?>
            </div><div class="col-lg-6">
        <?php endif; ?>

        <?php the_content(); ?>
    <?php ++$counter; endwhile; ?>
    </div>
</div>

try it like this

<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>
<div class="row">
   <div class="col-lg-6">
      <!-- The first half of the total loop count. -->
      <?php
      $i=0;
      while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++
          the_content();
      endwhile();
      ?>
   </div>
   <div class="col-lg-6">
      <!-- The second half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
</div>

https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM