How to Add Related Posts to WordPress Using Code
Implementing related post recommendations in WordPress is not difficult. You can use services like Baidu Recommendations, CNZZ Cloud Recommendations, or various plugins. While these methods are simple, they can impact page load speeds, which is often unacceptable for performance-conscious site owners.
Previously, Xiaoz Blog used CNZZ Cloud Recommendations and was quite satisfied. It only required adding a snippet of JavaScript code from the official source. For details, refer to Adding CNZZ Cloud Recommendations to Your Website to Enhance User Stickiness. However, since I enjoy tinkering, I have discontinued CNZZ and switched to implementing related posts via custom code. This approach offers greater customization and better performance.

This method works by retrieving the category ID of the current article and then fetching other articles within that same category. To implement this, add the following code to the appropriate location in the single.php file within your theme directory:
<ul id="cat_related">
<?php
global $post;
$cats = wp_get_post_categories($post->ID);
if ($cats) {
$args = array(
'category__in' => array( $cats[0] ),
'post__not_in' => array( $post->ID ),
'showposts' => 6,
'caller_get_posts' => 1
);
query_posts($args);
if (have_posts()) {
while (have_posts()) {
the_post(); update_post_caches($posts); ?>
<li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
}
else {
echo '<li>* No related articles available</li>';
}
wp_reset_query();
}
else {
echo '<li>* No related articles available</li>';
}
?>
</ul>
Once added, the functionality will be implemented, but the default output may look unappealing. If you are familiar with CSS stylesheets, you can customize the design to match your site's aesthetic. Below is the display effect used on Xiaoz Blog:

Reference: Several Methods to Generate Related Posts in WordPress Using Code