WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to display the links to all posts of the same category of the current post on that page. I wrote the following code in the single.php file.

<?php $categories_of_this_post = get_the_category(); ?>
<?php $fist_category_id = $categories_of_this_post['0']->term_id; ?>
<?php $this_post_ID = get_the_ID(); ?>
<div class="related-posts">
    <?php query_posts( array ( 'cat' => $fist_category_id, 'orderby' => 'date', 'order' => 'ASC' ) ); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <?php if (get_the_ID() != $this_post_ID) : ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <?php else : ?>
            <?php the_title(); ?>
            <?php endif; ?>
    <?php endwhile; else: ?>
    <p><?php _e('Sorry, no articles written under this category.'); ?></p>
    <?php endif; ?>

But this code returns all the posts found on the WordPress website. Where it goes wrong?

share|improve this question
Use get_posts() instead. – kaiser Jul 4 '12 at 11:16
Hello i have checked ur code. its showing all post of particular category. which category id is passed in query string – Arvind Pal Jul 4 '12 at 11:31
up vote 1 down vote accepted

I've not tested this, but the following is the method you shoulduse. Don't use query_posts.

 $cats_of_post= get_the_category();

      $cat_id = (int) $cats_of_post['0']->term_id;
      $related = get_posts(array(
           'numberposts'     => 5,
           'category'        => $cat_id,
           'orderby'         => 'post_date',
           'order'           => 'DESC',
           'exclude'         =>

       global $post;
       $temp_post = $post;?>

       <div class="related-posts">

       <?php if( $related ): ?>
               <?php foreach ($related as $post): ?>
                         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php endforeach; ?>

       <?php else: //No posts ?>
            <p><?php _e('Sorry, no articles written under this category.'); ?></p>

       <?php endif; ?>
       <?php $post = $temp_post; ?>
<?php }//Endif no $cats_of_post
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.