Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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">
    <ol>
    <?php query_posts( array ( 'cat' => $fist_category_id, 'orderby' => 'date', 'order' => 'ASC' ) ); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <li>
            <?php if (get_the_ID() != $this_post_ID) : ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <?php else : ?>
            <?php the_title(); ?>
            <?php endif; ?>
        </li>
    <?php endwhile; else: ?>
    <p><?php _e('Sorry, no articles written under this category.'); ?></p>
    <?php endif; ?>
    </ol>
</div>

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

1 Answer 1

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();

 if($cats_of_post){
      $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 ): ?>
               <ol>
               <?php foreach ($related as $post): ?>
                    <li>
                         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                <?php endforeach; ?>

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

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

Your Answer

 
discard

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.