Adding a row div after every four post in wordpress

I am trying to add a div class="row" after every four posts in my wordpress website. The following code is used to generate the post types on my page:

<?php 
    $temp = $wp_query; 
    $wp_query = null; 
    $wp_query = new WP_Query(); 
    $wp_query->query('showposts=8&post_type=branding'.'&paged='.$paged); 

    while ($wp_query->have_posts()) : $wp_query->the_post(); 
?>

<div class="col-md-3">
    <div class="featured-project-image">
        <?php 
            if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
                the_post_thumbnail();
            }
             else { echo'<img src="';
                 echo get_bloginfo( 'stylesheet_directory' ); 
                 echo'/images/placeholder.jpg"/>'; } ?>

    </div>
</div>

<?php endwhile;?>

Related posts

Leave a Reply

2 comments

  1. The following should do what you want

    <?php
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query();
    $wp_query->query('showposts=8&post_type=branding' . '&paged=' . $paged);
    ?>
    <div class="row">
    <?php
    $i = 0;
    while ($wp_query->have_posts()):
        $wp_query->the_post();
        if ($i == 4) {
            $i = 0;
            ?>
            </div>
            <div class="row">
            <?php
        }
        ?>
    
        <div class="col-md-3">
            <div class="featured-project-image">
                <?php
                if (has_post_thumbnail()) {
    
                    // check if the post has a Post Thumbnail assigned to it.
                    the_post_thumbnail();
                } 
                else {
                    echo '<img src="';
                    echo get_bloginfo('stylesheet_directory');
                    echo '/images/placeholder.jpg"/>';
                } ?>
                </div>
            </div>
        <?php
        $i++;
    endwhile; ?>
    </div>
    

    Starting the div before the while loop ensures the first 4 are also contained in a row.

  2. Create variable, iterate it in each loop step and check if % 4 == 0;:

    $i = 0;
    
    while (...) {
        echo $i % 4 == 0 ? 'row' : ''; // echo .row in first step too. If you want in the 4th step, just change the result of modulo operator
    
        // your code here
    
        $i++;
    }