WordPress: Show related posts by tags

June 29, 2020 Ken Fisher Loading... Post a comment

This article shows you how to display related posts by tags in WordPress.

Place the following snippet in your single.php where you want the related posts to show up (a good spot is right below your post content):

<!-- other code here -->
<?php
// retrieve all the tag's ids associated with the current post
$tags = wp_get_post_terms($post->ID, 'post_tag', ['fields' => 'ids']);

if ($tags) :
    $args = [
        'post_type' => ['post', 'piece', 'gallery', 'download'],

        // we don't want the current post to appear in the list of its related posts
        'post__not_in'        => get_the_ID(),

        // the number is totally up to you
        'posts_per_page'      => 8,

        // no sticky posts will be here
        'ignore_sticky_posts' => 1,

        'order'             => 'DESC',

        // focus on these lines
        'tax_query' => [
            [
                'taxonomy' => 'post_tag',
                'terms'    => $tags
            ]
        ]
    ];

    // QUERY
    $my_query = new WP_Query($args);
    if ($my_query->have_posts()) : ?>
        <h2>Related posts</h2>
        <ul>
        <!-- the while loop -->
            <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
                <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php endwhile; ?>
        </ul>
    <?php endif;
endif; ?>
<!-- other code here -->

In order to make your related posts look better, you should add some extra CSS styles.

guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x