0

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?

2
  • Use get_posts() instead.
    – kaiser
    Jul 4, 2012 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, 2012 at 11:31

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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