WordPress Loop: Wrap 3 search results in a row

I have set up my template to output search entries in col-4 to make a 3 column layout, and I need to wrap each set of 3 in a row.

I have come up with the below but it seems my opening and closing PHP is wrong, as I am currently getting each 1 search entry in it’s own row. Thanks in advance for help

<?php 
if ($counter % 3 == 0) { 
  echo '<div class="row">';
} ?>


<article id="post-<?php the_ID(); ?>" class="search-result col-md-4">
    <?php
    $entry_thumbnail = racks_entry_thumbnail();
    $entry_class = $entry_thumbnail ? 'search-thumbnail' : 'col-sm-4 col-md-4';
    ?>
        <?php if( $entry_thumbnail ) : ?>
            <div class=" <?php echo esc_attr( $entry_class ); ?>">
                <?php echo $entry_thumbnail; ?>

            <header class="entry-header clearfix">
                <h2 class="entry-title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title() ?></a></h2>
                </header>

        <div class="entry-summary">
          <?php the_excerpt(); ?>
        </div>

        <footer class="entry-footer">
          <a class="read-more" href="<?php the_permalink() ?>"><?php _e( 'Read more', 'racks' ) ?></a>
        </footer>

    </div>
        <?php endif;?>
    <div class="clearfix"></div>
</article><!-- #post-## -->

<?php $counter++ ; echo '</div>'; ?>

Related posts

1 comment

  1. Don’t forget you only have to close </div> for $counter divisible by 3:

    <?php 
      echo ($counter % 3 === 0) ? '</div>' : '';
      $counter++;
    ?>
    

    As it stands, you close </div> at each step of your loop. Also note that you might want to make this check right at the beginning of the iteration, assign its result into a variable. For example:

    <?php
    
    $counter = 0;
    while ($counter < someLimit):
      $newRow = $counter % 3 === 0;
    
    ?>
    
      // at the beginning of template:
      <?= $newRow ? '<div class="row">' : ''; ?>
    
      // output goes here
    
      // at the end of template:
      <?= $newRow ? '</div>' : ''; ?>
    
    <?php endwhile; ?>
    

    Another approach would be using output buffer to store the output for each element in some array, split this array into chunks (with array_chunk()), then output those chunks (wrapping each one in <div class="row"></div> structure).

Comments are closed.