Display Related Posts

Show related posts at the end of each post.

<?php
function display_related_posts() {
    if (is_single()) {
        $categories = get_the_category();
        if ($categories) {
            $category_ids = array();
            foreach ($categories as $category) $category_ids[] = $category->term_id;

            $args = array(
                'category__in'   => $category_ids,
                'post__not_in'   => array(get_the_ID()),
                'posts_per_page' => 3
            );
            $related_posts_query = new WP_Query($args);

            if ($related_posts_query->have_posts()) {
                echo '<div class="related-posts"><h3>Related Posts</h3><ul>';
                while ($related_posts_query->have_posts()) {
                    $related_posts_query->the_post();
                    echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                echo '</ul></div>';
                wp_reset_postdata();
            }
        }
    }
}
add_action('the_content', 'display_related_posts');
?>

Post Comment