How to Show Related Posts Based on the Category in WordPress

You Also Might LikeBefore you start reading, go all the way bottom of this post and take a look at the “You Also Might Like” section. You will find the list of some post which were posted on that same category of this Post.

Every time you are Posting something, I assume you are picking any Specific category where your Post belongs to. This is a Crucial part of Your Blog. Why? If everything works fine, definitely Google will crawl your new post at some point. If someone finds your post from Google’s search result, he or she might take a look at some other Posts related with the same category that he or she was looking for.

Adding “You Also Might Like” section will definitely help your reader to access more of your Posts and this a great way to keep your visitors exploring your great site.

Now the Question is, How exactly you can display related posts based on the Category of your current post? It’s pretty simple.
Step 1: Log in to your WordPress site.
Step 2: From “Appearance” menu, go to “Editor”.
Step 3: Select “single.php” file and copy the following code.

<?php
$max_articles = 6; //number of articles are displayed
$cnt = 0;
$article_tags = get_the_category();
$tags_string = '';
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) { $category_string .= $category->cat_ID . ','; }
$cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post){
$cnt ;
if ($cnt > $max_articles) break;
echo '<li>';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo $related_post->post_title . '</a></li>'; } } }
?>

Step 4: Paste the code within a DIV element (below the DIV element associated with <?php the_content(); ?> function) and Update the page.

You are pretty much done. All you have to do now is to style them with CSS code. I used the following code. You can simply follow that or can do it on your own way.

#related-post { margin-top: 5px; border-bottom: solid 1px #cdcdcd;}
#related-post h3 {font-family: arial; font-size: 20px; color: #555555; font-weight: bold;}
#related-post ul { margin:0; padding: 0;}
#related-post ul li { list-style-type: none; margin:0; padding: 4px; font-family: verdana, tahoma; font-size: 15px; }

I hope it was a helpful post for you. If you like our Post, show your Support (Like us on Facebook, follow us on Twitter etc.) Oh, ya feel free to make comments or ask questions if you can’t make it work for some reason. Thanks.

You can follow us on Twitter, add on your Google+ circle or Like our Facebook page to get the latest news, updates and reviews.

advertisement
Comments: