Display Related Posts Based On Category Without Plugin

If you looking for display related posts on your post/view page? then here we have a solution to display the related posts based on category in your WordPress site. Without plugin is always the best way I recommend you because this only helps you to maintain your website performance.
Use the below code in your end of post content on a single.php (Single Post) template. This will display a maximum of 5 related posts on your single.php page, if you like to increase the post then you can change ‘numberposts’ count also any other customization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $relatedPost = get_posts(array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array( $post->ID ) )); if ($relatedPost) foreach ($relatedPost as $post) { setup_postdata($post); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <?php the_content(); ?> </li> <?php } wp_reset_postdata(); ?> |
The above code will display the related post title and content. If you like to display any other things ( for example Image and Short Content of the post ) the following will help you.
Display and Short your WordPress Post Content
If you like to reduce the content in the related posts use the below code that will help you to short your content. By using excerpt you can reduce the content, you just paste the below code instead of the_content function.
1 |
<?php echo get_excerpt(100); ?> |
Related Post Featured Image Dispaly In WordPress
Use the below code between the related post loop above or below the the_title function. This will help you to get the featured image from the post page.
1 |
<?php the_post_thumbnail('delicious-recent-thumbnails'); ?> |
Conclusion:
I hope this article will help you get the related posts based on the category with the few lines of code. If you have any doubts let me know in the comment section and if you loved this article share it with your friends.
Related PostsWithout Pluginwordpress
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]