How to add Related Posts with thumbnail without plugin

Using this snippet you will be able to add to your template a related posts function with thumbnail (if “Use as featured image” are selected) without plugins.

You can insert this code in your single.php file, or in custom post type.

Please do a single.php backup before apply for this code.

<?php
$backup = $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

$args=array(
'tag__in' => $tag_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);
if( $my_query->have_posts() ) {
echo '<h2>Related Posts</h2><ul class="relatedPosts">';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><?php the_post_thumbnail(array(40,40)); ?><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}

$post = $backup;
wp_reset_query();
?>

Pigi

Blogger, Trainee Lawyer and Wordpress Lover, and Yes, Wpcode.net Owner :D

You may also like...

11 Responses

  1. hi,

    i am using theme :yoko and am unable to find the single.php file ,can u please guide me on how to do this

    Thanks fr the help in advance.

    • Pigi says:

      Hi, yoko uses a different but common system for template, to edit the single file you just need to open file called “content-xxxxx.php”.
      Be careful, the “xxxxx” string depends from the type of post, so:

      • content-single.php is for the common posts
      • content-video.php is for posts marked as video

      just browse yoko’ theme folder in “yourblog.com/wp-content/themes/yoko” and open the right file.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>