How to place a loop within another loop?

Try this: We declare an incrementer at the top of our outter loop called $popularLoop to keep track of how many popular loops we’ve been through, we assume we’re going to at least hit 1.

Inside our Inner Loop (popular) we need to set how many posts per page we’re going to load, multiple that by how many popular loops we’ve been through and that is going to give us our offset. At the end of our Inner Loop we increment $popularLoop so our offset stays consistent:

<div class="content">

    <div class="posts latest">

        <?php

        $args1 = array (
            'posts_per_page'    => 1000000,
            'order'             => 'DESC',
            'orderby'           => 'date'

        );

        $latest = new WP_Query( $args1 );
        $popularLoop = 0;

        if ( $latest -> have_posts() ) :

            $count = 0;

            while ( $latest -> have_posts() ) : $latest -> the_post();

                $count++;

                if ( $count % 5 == 0 ) :

                        get_template_part( 'template', 'post' ); ?>

                        </div> <!--/posts-latest-->

                        <div class="posts popular">

                            <?php
                            $popular_ppp = 10;
                            $popularOffset = $popular_ppp * $popularLoop;
                            $args2 = array (
                                'posts_per_page'    => $popular_ppp,
                                'offset'            => $popularOffset,
                                'order'             => 'ASC',
                                'orderby'           => 'date',
                            );

                            $popular = new WP_Query( $args2 );

                            if ( $popular -> have_posts() ) :

                                while ( $popular -> have_posts() ) : $popular -> the_post();

                                    get_template_part( 'template', 'post' );

                                endwhile;

                              $popularLoop++;
                            endif;

                            ?>

                        </div> <!--/posts-popular-->

                        <div class="ad-block">
                            <?php get_template_part( 'template', 'ad' ); ?>
                        </div>

                    </div><!--/content-->    

                    <div class="content">

                        <div class="posts latest">

                <?php

                else :

                    get_template_part( 'template', 'post' );

                endif;

            endwhile;

        endif; wp_reset_postdata();

        ?>

    </div> <!--/posts-latest-->    

</div>

Leave a Comment