I have somehow managed to create this code to display Related Posts by category on single post page.

<div class="relatedposts">
 <h3>You might also like</h3>
        $orig_post = $post;
        global $post; 
        $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'=> 4, // Number of related posts that will be shown.

          $my_query = new wp_query( $args );
          while( $my_query->have_posts() ) {

       <div class="relatedthumb">
              <a rel="external" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" title ="<?php the_title(); ?>" ><?php the_post_thumbnail(); ?><br /><?php the_title(); ?></a>

      <?php } // ending while loop

$post = $orig_post;

Problem is, this code doesn't displays related posts of the same category as on single post page. Even includes the same post displayed on single post page and also shows some recent posts.

You can test yourself. Please suggest how can I resolve this or am I missing some thing in this code?


  • 1
    And what DOES it display? PS. You should use posts_per_page and not showposts param (the latter one is deprecated). – Krzysiek Dróżdż Jul 17 '13 at 9:12
  • sometimes category unrelated, sometimes recent and some category related all in 4 posts. – busyjax Jul 17 '13 at 10:12
  • Do you call this inside loop? – Krzysiek Dróżdż Jul 17 '13 at 10:55
  • No, this is shown after post content – busyjax Jul 17 '13 at 11:02
  • Are you sure that global $post has correct value, when you call this code? It can be changed by some other part of code (so $post is not the post which content is displayed)... – Krzysiek Dróżdż Jul 17 '13 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.