Related Posts By Category For Single.php, Exclude Current Single Post

Show a loop of related articles on the sidebar of single.php (or any single post template sidebar), but exclude the current single post from the related loop. This code goes in the sidebar of a single template file of a WordPress theme. Related articles, for this code, are posts within the same category of the current single post being viewed. (To get related posts of custom post types, see Get Related Posts For Custom Post Type By Category. )

In the example below, you can modify the HTML on line 25 to display the thumbnails, and/or excerpts, depending on your preferences. Left as it, it will show a list of the titles of 3 related posts.

$categories = get_the_category($post->ID);
if ( $categories ) {
	$category_ids = array();
	foreach ( $categories as $individual_category ) {
		$category_ids[] = $individual_category->term_id;
		'category__in' => $category_ids,
		'post__not_in' => array($post->ID),
		'showposts'=>3, // Number of related posts that will be shown.
	$my_query = new wp_query( $args );
	if( $my_query->have_posts() ) {
		echo '<h3>Related Articles</h3>'; // You can edit this
		echo '<ul>';

		while ($my_query->have_posts()) {
			<!-- do stuff -->

			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>


		echo '</ul>';

See more: ,


We've 3 Responses

  1. June 25th, 2012 at 11:52 pm

    How would you change the code to use it on single-custom.php
    with custom post type “bags”
    and custom taxonomy:
    1. material
    1.1 Leather
    1.2 Plastic
    1.3 Paper

    I need to show below the single-post all the other custom-post from the product taxonomy :S

    Ej: Single-custom.php show bag with leather taxonomy.
    I need to show below all the other custom-post with the same taxonomy

    I have so far this:

    ‘bags’, ‘posts_per_page’ => 100 ) ); ?>

    have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>

    <a class="thumb-bag" href="”>


Leave a Reply to funky Cancel reply

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: