3
    <?php
      $args = array(
      'post_type' => 'college',
      'posts_per_page' => -1,
      'order' => 'DESC',
      'orderby' => 'menu_order'
      );

      $the_query = new WP_Query( $args );
      if ( $the_query->have_posts() ) :
      while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

      <div class="col-3">
        <?php the_title(); ?>
      </div>

   <?php
   endwhile;
   endif;
   wp_reset_postdata();
   ?>

Hi, I've never done this before. I'm trying to wrap every 4 posts in the loop above inside a <div class="row"></div>

2 Answers 2

9

This should sort you out

$args = array(
    'post_type' => 'college',
    'posts_per_page' => -1,
    'order' => 'DESC',
    'orderby' => 'menu_order'
);

$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
    $counter = 0;
    while ($the_query->have_posts()) : $the_query->the_post();
        if ($counter % 4 == 0) :
            echo $counter > 0 ? "</div>" : ""; // close div if it's not the first
            echo "<div class='row'>";
        endif;
        ?>
        <div class="col-3">
            <?php the_title(); ?>
        </div>
        <?php
        $counter++;

    endwhile;
endif;
wp_reset_postdata();
?>

Adapted from Wrapping a div around every third item in a foreach loop PHP

Sign up to request clarification or add additional context in comments.

1 Comment

Great :) it was a nice challege, had me scribbling a few stuff
1

You can follow my code, post of @chapskev is good but missing a closing div after end if

<?php $counter = 0; // 4  per list ?>
<?php foreach ($arr as $key => $value) {
  if ($counter % 4 == 0) :
    echo $counter > 0 ? "</div>" : ""; // close div if it's not the first
    echo "<div class='group'>";
  endif;
  echo 
  <<<TEXT
  <span>content</span>
  TEXT;
  $counter++;
  }
  echo "</div>";
?> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.