How to Display Related Posts by Category in WordPress

Home » Snippets » How to Display Related Posts by Category in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you hoping to improve your website’s user experience by presenting your visitors with related posts based on categories? Knowing that your readers are more likely to stay around if they can easily find more content related to what they’re initially interested in, it becomes crucial to implement a ‘related posts’ feature on your WordPress site. In this article, we will guide you through the steps to easily display related posts in the same category.

					function wpturbo_related_posts_by_category() {
    global $post;
    
    $cats = wp_get_post_categories($post->ID);

    $related_posts = new WP_Query( array(
        'category__in' => $cats,
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
    ));

    if( $related_posts->have_posts() ) {
        echo '<div class="wpturbo-related-posts">';
        echo '<h3>Related Posts</h3>';
        while( $related_posts->have_posts() ) {
            $related_posts->the_post(); ?>

            <div class="related_post">
                <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
                    <?php the_title(); ?>
                </a>
            </div>

        <?php }
        echo '</div>';
    }
    wp_reset_postdata();
}

add_action( 'the_content', 'wpturbo_related_posts_by_category' );
```
The above code register a new function called `wpturbo_related_posts_by_category` and append the function after the content of each post using `the_content` action hook. Inside the function, it fetches the category of the current post and queries 5 posts that share the same category. Then it loops through each related post and displays them.
				

To start understanding the code snippet, we need to dissect the wpturbo_related_posts_by_category function.

The first line refers to the $post global variable to retrieve the specific data of the post currently being viewed.

global $post;

The next line uses the wp_get_post_categories function which fetches all categories associated with the current post and store these in the $cats variable.

$cats = wp_get_post_categories($post->ID);

The $related_posts variable then uses WP_Query to form a custom WordPress query, filtering posts to those which fall under the categories obtained in the previous step but excluding the current post.

$related_posts = new WP_Query( array(
    'category__in' => $cats,
    'post__not_in' => array($post->ID),
    'posts_per_page' => 5,
));

However, if there are no associated posts in the categories specified, no output will be produced. This is ensured through the conditional line if($related_posts->have_posts()).

Once this condition passes verifying related posts, we open a div for related posts and then continue with a while loop which is used to output data for each related post while there are posts available. Each related post is displayed within a div with a link to the post and its title.

if( $related_posts->have_posts() ) {
    echo '<div class="wpturbo-related-posts">';
    echo '<h3>Related Posts</h3>';
    while( $related_posts->have_posts() ) {
        $related_posts->the_post(); ?>

        <div class="related_post">
            <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
                <?php the_title(); ?>
            </a>
        </div>

    <?php }
    echo '</div>';
}

Lastly, wp_reset_postdata() function is used to reset the global $post variable back to the current post in the main query. This ensures that the main query loop is not interrupted or modified by our custom query.

wp_reset_postdata();

To display the related posts on each post, add_action is used to call wpturbo_related_posts_by_category function after the content of each post as so.

add_action( 'the_content', 'wpturbo_related_posts_by_category' );

And thus, this sums up how our code snippet displays related posts by the same categories.

Register an account to save your snippets or go Pro to get more features.