Display related posts by tags in WordPress without plugin

Saul Goodman September 15, 2019 Loading...

Put the code below where you want to display related posts in your single.php file.

<?php
    $tags = wp_get_post_terms($post->ID, 'post_tag', ['fields' => 'ids']);
    if ($tags) :
        $args = [
            'post_type' => 'post',
            'posts_per_page'      => 8,
            'ignore_sticky_posts' => 1,
            'orderby' => 'ID',
            'order'  => 'DESC',
            'tax_query' => [
                [
                    'taxonomy' => 'post_tag',
                    'terms'    => $tags
                ]
            ]
        ];
        $my_query = new WP_Query($args);
        if ($my_query->have_posts()) : ?>
            <h2>Related posts:</h2>
            <div class="related-posts">
                <?php while ($my_query->have_posts()) :
                    $my_query->the_post(); ?>
                    <h3 class="related-post-title">
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </h3>
            </div>
        <?php endwhile; ?>
        </div><!-- end related-posts-->
<?php endif;
    wp_reset_postdata($my_query);
endif; ?>

avatar
Welcome to KINDACODE. Have a nice day and code well!