user38208
user38208

Reputation: 1094

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

Upvotes: 1

Views: 2214

Answers (2)

enigma
enigma

Reputation: 3491

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.

Upvotes: 3

pavel
pavel

Reputation: 27072

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++;
}

Upvotes: 0

Related Questions