Dynamically inserting a div class in wordpress

I have a custom post type in wordpress and i use the following code to display the 6 thumbnails of the custom post type in this case package in category South Africa in a wordpress page:

<?php 
     $args = array('post_type' => 'package','package-category'=>'South Africa',   'posts_per_page'=>6 );
     $loop = new WP_Query( $args );
     while ( $loop->have_posts() ) : $loop->the_post();
?>

<div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
                 <?php the_post_thumbnail(); ?>
            </div>
    </div>

Currently the thumbnails are displayed correctly and are displayed in three i.e 3 thumbnails each with a coloumn width of 33% in the first row and 3 in the second row.

Read More

I would like to dynamically insert a div class="row" such that the every 3 thumbnails is placed in this class. The html rendered would be as follows:

 <div class= "row">
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="1.jpg">
            </div>
  </div>
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="2.jpg">
            </div>
  </div>
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="3.jpg">
            </div>
  </div>
 </div>

<div class= "row">
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="4.jpg">
            </div>
  </div>
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="5.jpg">
            </div>
  </div>
  <div class="four columns gdl-package-grid2">
    <div class="package-content-wrapper">
               <img src="6.jpg">
            </div>
  </div>

 </div>

Related posts

Leave a Reply

1 comment

  1. You could simply use a variable to keep track of the loop and add the appropriate HTML tags as follows:

    <?php 
        $args = array(
            'post_type' => 'package',
            'package-category' => 'South Africa',
            'posts_per_page' => 6
        );
        $loop = new WP_Query($args);
        $loop_count = 0;
    ?>
    <?php while ($loop->have_posts()) : $loop->the_post(); ?>
        <?php
            $loop_count++; // Increase Loop Count
            $loop_count = ($loop_count > 3) ? 1 : $loop_count; // Reset to 1 if > 3
        ?>
        <?php if ($loop_count === 1) : ?>
            <div class="row">
        <?php endif; ?>
    
        <div class="four columns gdl-package-grid2">
            <div class="package-content-wrapper">
                 <?php the_post_thumbnail(); ?>
            </div>
        </div>
    
        <?php if ($loop_count === 3) : ?>
            </div>
        <?php endif; ?>
    <?php endwhile; ?>
    

    I hope it helps!