Break WordPress post loop and continue it

I have a WordPress blog that shows the last 10 posts on the main page:

 <main id="main" class="site-main" role="main">

            <?php if ( have_posts() ) : ?>

                    <?php /* Start the Loop */ ?>
                    <?php while ( have_posts() ) : the_post(); ?>

                            <?php

                                    get_template_part( 'content', get_post_format() );
                            ?>

                    <?php endwhile; ?>

I want to break the loop after 5 posts, put another code (a widget that I wrote), then continue the loop and display the rest of the posts, so my main page will be like:
5 Recent posts -> widget -> the next 5 posts.
I manged to display the recent 5 posts, but can’t display the 5 next posts.
Anyone have an idea? 🙂

Related posts

1 comment

  1. Just include your widget after the 5th post has been shown; no need to break up the loop. Use a counter and check when the 5th post is displayed.

    Change this:

    <?php while ( have_posts() ) : the_post(); ?>
    
        <?php get_template_part( 'content', get_post_format() ); ?>
    
    <?php endwhile; ?>
    

    To:

    <?php $count = 1;
    while ( have_posts() ) : the_post(); ?>
    
        <?php 
        get_template_part( 'content', get_post_format() );
    
        if ( 5 === $count ) {
    
            // code to display beneath 5th post.
    
        }
    
        $count++; ?>  
    
    <?php endwhile; ?>
    

Comments are closed.