Juárez
Juárez

Reputation: 131

Query related posts, Wrap in Row every 3 posts

I'm trying to query some related posts and wrap them in a row div every 3 posts. I've checked all the questions regarding this but still my query renders a mess. This is what I have so far:

<?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );
$counter=0;
if( $related ) foreach( $related as $post ) {
setup_postdata($post); $counter++;
 ?>

<div class="row">
    <article class="third-width">
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">           
            <?php  the_post_thumbnail('post-parrilla'); ?>
        </a>
<?php exclude_post_categories("8"); ?>
<div class="clear"></div>
    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">           
        <div class="post-title">
        <span><?php the_title(); ?></span>
        </div>
    </a>
    </article>

<?php if ($counter%3==0):?>
    </div><div class="row"> 
<?php endif;?>
<?php } wp_reset_postdata(); ?>

Thank you in advance

Upvotes: 0

Views: 72

Answers (1)

Shital Marakana
Shital Marakana

Reputation: 2887

Use below code

 <?php
$related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 6,
'post__not_in' => array($post->ID) ) );

if( $related ) 
{
    $counter = 0;
    ?>
    <div class="row">
    <?php
    foreach( $related as $post ) {
    setup_postdata($post); 

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

        <article class="third-width">
            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">           
                <?php  the_post_thumbnail('post-parrilla'); ?>
            </a>
    <?php exclude_post_categories("8"); ?>
    <div class="clear"></div>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="third-link">           
            <div class="post-title">
            <span><?php the_title(); ?></span>
            </div>
        </a>
        </article>

     <?php
     $counter++;
    } 
    ?>
    </div>
    <?php
}
wp_reset_postdata(); 
?>

Upvotes: 2

Related Questions