Custom Query with WP_Query for Related Posts

Display related posts based on custom query parameters.

<?php
function display_related_posts() {
    if (is_single()) {
        global $post;
        $categories = wp_get_post_categories($post->ID);
        $args = array(
            'category__in' => $categories,
            'post__not_in' => array($post->ID),
            'posts_per_page' => 5,
            'orderby' => 'rand'
        );
        $related_posts = new WP_Query($args);
        
        if ($related_posts->have_posts()) {
            echo '<div class="related-posts"><h3>Related Posts</h3><ul>';
            while ($related_posts->have_posts()) {
                $related_posts->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul></div>';
            wp_reset_postdata();
        }
    }
}
add_action('wp_footer', 'display_related_posts');
?>

Post Comment