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 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>
      <?php
        $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;

          $args=array(
            'category__in' => $category_ids,
            'post__not_in' => array($post->ID),
            'showposts'=> 4, // Number of related posts that will be shown.
            'caller_get_posts'=>1);

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

       <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>
       </div>

      <?php } // ending while loop
       }

$post = $orig_post;
wp_reset_query();
?>
</div>

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?

Thanks

share|improve this question
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

 
discard

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

Browse other questions tagged or ask your own question.