Created a nested Loop inside the main Loop to display related posts based on tags in WordPress.

Nested Loop can be created inside WordPress theme templates using a combination of the main Loop and separate WP_Query instances. We can create a nested Loop to display related posts based on tags.

Use the following codes:-

<?php
            if( have_posts() ):
                while( have_posts() ): the_post();
                    //loop content(template tags,html,etc)
                    ?>
                    <h1><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
                    <?php the_content();
                    $tags= wp_get_post_terms(get_the_ID());
                    if($tags){
                        echo "Related jjjjPosts";
                        $tagcount = count ($tags);
                        for($i=0; $i< $tagcount;$i++){
                            $tagIDs[$i] = term_id;
                        }
                        $args =  array(
                            'tag_in' => $tagIDs,
                            'post__not_in'=> array('$post->ID'),
                            'posts_per_page' => 2,
                            'ignore_sticky_posts' =>1
                        );
                         $relatedPosts = new wp_Query($args);
                        if($relatedPosts->have_posts()){
                            //loop through related posts based on the tag
                            while($relatedPosts->have_posts()) :
                                $relatedPosts->the_post(); ?>
                                <p><a href="<?php the_permalink(); ?>">
                                        <?php the_title(); ?></a></p>
                            <?php endwhile;
                        }
                    }

                endwhile;
            endif;

            ?>


 

This code will display all of posts as normal post.Inside the main loop,check if any contain any of the same tags as main post.If so, display the latest five posts that match as related post.If there no posts match,the related post section will no display.

Total Page Visits: 2263 - Today Page Visits: 1

Leave a Reply