Posted By

jwaldeck on 02/01/12


Tagged

wordpress


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfolt


Related Posts by Category (with images)


 / Published in: PHP
 

URL: http://www.wpbeginner.com/wp-themes/how-to-add-related-posts-with-a-thumbnail-without-using-plugins/

Insert inside the loop

  1. <?php $orig_post = $post;
  2. global $post;
  3. $categories = get_the_category($post->ID);
  4. if ($categories) {
  5. $category_ids = array();
  6. foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
  7.  
  8. $args=array(
  9. 'category__in' => $category_ids,
  10. 'post__not_in' => array($post->ID),
  11. 'posts_per_page'=> 2, // Number of related posts that will be shown.
  12. 'caller_get_posts'=>1
  13. );
  14.  
  15. $my_query = new wp_query( $args );
  16. if( $my_query->have_posts() ) {
  17. echo '<div id="related_posts"><h3>Related Posts</h3><ul>';
  18. while( $my_query->have_posts() ) {
  19. $my_query->the_post();?>
  20.  
  21. <li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
  22. <div class="relatedcontent">
  23. <h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
  24. <?php the_time('M j, Y') ?>
  25. </div>
  26. </li>
  27. <?
  28. }
  29. echo '</ul></div>';
  30. }
  31. }
  32. $post = $orig_post;
  33. wp_reset_query(); ?>

Report this snippet  

You need to login to post a comment.