Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

How to Show Related Posts by Category in WordPress

Last updated on:

As you can see at the bottom of the posts on WPExplorer I show links to “Related Posts” which are gathered randomly from the same category as the current post. For today’s WordPress code trick I will show you how to create the loop to get posts from the current category and display a list of random links below your posts so you don’t have to use any plugin.

Related Posts From Category Loop

Simply paste the following loop wherever you want your related posts to appear. Basically the code generates an array of the current post categories and then it queries the database to get other items within these categories. Previously this article showed how to get posts only from the first category, but this method was probably not the best way to display related items. By grabbing posts from all the categories of the current post it will allow your blog to display more unique “related” sections as well as if you don’t have a lot of items in one specific category it will be able to display posts from another related one.

<?php
// Default arguments
$args = array(
	'posts_per_page' => 4, // How many items to display
	'post__not_in'   => array( get_the_ID() ), // Exclude current post
	'no_found_rows'  => true, // We don't ned pagination so this speeds up the query
);

// Check for current post category and add tax_query to the query arguments
$cats = wp_get_post_terms( get_the_ID(), 'category' ); 
$cats_ids = array();  
foreach( $cats as $wpex_related_cat ) {
	$cats_ids[] = $wpex_related_cat->term_id; 
}
if ( ! empty( $cats_ids ) ) {
	$args['category__in'] = $cats_ids;
}

// Query posts
$wpex_query = new wp_query( $args );

// Loop through posts
foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
	
	<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>

<?php
// End loop
endforeach;

// Reset post data
wp_reset_postdata(); ?>

Display Related Posts Via A Plugin

Yet Another Related Posts Plugin

The guide above shows you how to display related posts via custom code in your theme. However, you can also display related posts via a plugin. There are many great WordPress related posts plugins but one of the most popular ones is the “Yet Another Related Posts Plugin (YARPP)”. This plugin uses advanced code to formulate your related posts and it has various options you can use to customize things, plus there is a Pro version available you can purchase for added features.

Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

26 Comments

  1. john

    Thanks for the great code, I used on my site and it’s working great.

    Please tell me what i need to add to show me from the last 10 posts from one category…the code above show random post from the entire and I only want to show from the last 10 posts.

    Thanks !

    • AJ Clarke

      Remove “&orderby=rand” that’s the code telling it too choose random posts. Then change numberposts=3 to numberposts=10 to select the last 10 posts.

      • sayandeep ghosh

        What do I have to do in order to get the posts from the same category and display them as related posts?

        • AJ Clarke

          That is exactly what this whole post is showing you how to do 😉

  2. genniecooperYoshikins

    I’m having the same problem as sayanddepp ghosh. All I get is a list of every post, not a list of the posts specific to the current category.

    • AJ Clarke

      I just updated the post to show a better method of retrieving related posts based on the current post category.

  3. Lars

    Hi, thank you for the code! The new version is working, but it responds always the same and newest posts of the category. Can you add the random order to the new code too?

    • AJ Clarke

      Yes, simply add orderby => ‘rand’ to the arguments array. Have a look at the WP_Query CODEX page to learn more about the function and all the available arguments you can use.

  4. karu

    I copy pasted it. But it does not work at all for some reason. Anything missing in this code?

    • AJ Clarke

      The code is correct and should work. I double checked it. Even if there aren’t “related” posts it should still display 4 posts. Do you have enough posts on your site? Also if you are trying to target a different post type or taxonomy sure you edit the code accordingly.

  5. Johann

    I like this solution, but my related posts are shown in an ongoing row.
    How can i show one post per line?
    And how can I add a headline like your “Related Articles”?
    Would be so thankfull if I could get this work.

    • AJ Clarke

      To change the way they look you will have to use CSS. Adding a heading is as easy as just adding some html at the top for your heading. Example:

      Related Posts

  6. c1b3r3y3

    Hi, this code works perfectly, but in the related posts only shows the posts published recently, how can I change it to display random posts inside that category?

    PS: Sorry for my english.

    • AJ Clarke

      All you need to do is add ‘orderby’ => ‘rand’ to the array to display random posts.

      • c1b3r3y3

        Thanks, now it works like I want.

  7. lordlupach

    I changed the loop and now the error that I get on the top of the sidebar shows different posts, but the_permalink and the_title still don’t work, I get this as a result..just like that, it even breaks the href, any help?

    • AJ Clarke

      Unfortunately your code was stripped out of the comment 🙁 I’ve recently updated this post though if you want to see my updated code and if it works better for your needs.

  8. Guy Abeho

    Thank you so much! works like a charm

  9. opmsongsblog

    How to put this on a function so that I can make a plugin?

    • AJ Clarke

      You just have to wrap it like this….

      function your_function_name() {
      // Place snippet code here without the opening and closing PHP tags
      }
      
  10. Tuta

    How do I style it like how you have done with wp-explorer? Am a beginner in css

    • Kyla

      Hi Tuta! We actually use a custom theme that we built and designed just for our own use, but there are tons of great free themes you can customize on your own to create your website. Start with a free theme from WordPress.org and create a child theme to start making changes with CSS. Then you can also install a free page builder plugin like Elementor to start creating your own custom page layouts. Best of luck!

  11. Tuta

    Thank you Kyla, What I really meant is how you style your related articles. Is it possible to get that css? I get horizontal related articles when i use the code above.

    • Kyla

      Ah I see. Unfortunately that’s part of our custom theme so I don’t want to copy and paste, but if we change our site design maybe we’ll consider releasing our old design as a theme 😉

  12. Gilbert

    What if I want to exclude certain category on it. (e.g. i dont want to see related post for “competitions” category)

    • AJ Clarke

      To exclude a category in a WordPress query you can use the ‘category__not_in’ parameter. Must like in the code snippet where we used category__in you would do the same but using category__not_in with an array of categories to exclude.

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.