Category Foreach keeps looping?

I’m using the following code to acquire all the child categories of a category and displaying the child posts of the child categories.

<?php
$cats = get_categories( 'child_of='.get_query_var( 'cat' ) );

foreach ( $cats as $cat ) :

    $args = array(
        'posts_per_page' => 3, // max number of post per category
        'category__in'   => array( $cat->term_id )
    );
    $my_query = new WP_Query( $args ); 

    if ( $my_query->have_posts() ) :
        echo '<h3>'.$cat->name.'</h3>';
        ?>

        <?php while( $my_query->have_posts() ) : $my_query->the_post(); ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <br />  
        <?php endwhile; ?>

    <?php else : ?>
        No Posts for <?php echo $cat->name; ?>
    <?php endif; ?>
<?php endforeach; ?>

and i want to acquire this output.

Read More
 Cat Child 1
 -Post1 Child 1
 -Post2 Child 1
 -Post3 Child 1
 -So on... .

 Cat Child 2
 -Post1 Child 2
 -Post2 Child 2
 -Post3 Child 2
 -So on... .

But instead of that, both the child categories are being repeated over and overagain. Can anybody tell me what the problem is? This is the output I have now.

 Cat Child 1
 -Post1 Child 1
 -Post2 Child 1
 -Post3 Child 1
 -So on... .

 Cat Child 2
 -Post1 Child 2
 -Post2 Child 2
 -Post3 Child 2
 -So on... .
 Cat Child 1
 -Post1 Child 1
 -Post2 Child 1
 -Post3 Child 1
 -So on... .

 Cat Child 2
 -Post1 Child 2
 -Post2 Child 2
 -Post3 Child 2
 -So on... .
 Cat Child 1
 -Post1 Child 1
 -Post2 Child 1
 -Post3 Child 1
 -So on... .

 Cat Child 2
 -Post1 Child 2
 -Post2 Child 2
 -Post3 Child 2
 -So on... .

until it loops 9 times and stops. what is the problem?

Related posts

Leave a Reply

1 comment

  1.    <?php  $cats = get_categories('child_of='.get_query_var('cat')); 
    
       foreach ($cats as $cat) :
    
      $args = array(
      'posts_per_page' => 3, // max number of post per category
      'category__in' => array($cat->term_id)
       );
       $my_query = new WP_Query($args); 
    
        if ($my_query->have_posts()) : 
        echo '<h3>'.$cat->name.'</h3>';
    
        while ($my_query->have_posts()) : $my_query->the_post(); ?>     
        <?php /*general loop output; for instance: */ ?>
        <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>    <br />  
    
        <?php endwhile; ?>
    
        <?php else : 
        echo 'No Posts for '.$cat->name;                
        endif; 
        wp_reset_query();
        endforeach; ?>
    

    use wp_reset_query(); before endforeach for reset WP_Query.