Разбейте цикл пополам, если число циклов четное - PullRequest
0 голосов
/ 14 мая 2019

Я хочу разбить цикл на половину общего количества циклов.Если общее количество циклов нечетное, я хотел бы удалить последний элемент массива, чтобы сделать общее количество циклов четным, и добавить удаленный элемент во вторую половину.

Вот структура кода, демонстрирующая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>

Я не знаю, как управлять циклом на основе моих упомянутых условий.Вот почему я не мог попробовать петлю контроля.

Ответы [ 2 ]

1 голос
/ 14 мая 2019

в одном цикле.Надеюсь, это сработает.Не могу проверить, так что позвольте мне, если вы столкнетесь с любой ситуацией.

<?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>
0 голосов
/ 14 мая 2019

попробуй вот так

<?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

...