HostOnNet Blog

Related posts with thumbnails in WordPress without plugin

Looking for Linux Server Admin or WordPress Expert? We can help.

related-post

The below code fetches the posts based on the tags. If you have enough tags added to each of your posts/pages then this code can be a good option for you.

It checks the tags assigned to the current post and then it fetches the posts linked to those tags. We have used an orderby attribute, which would ensure that the posts would not be fetched in an any particular order. This would be useful to show different related posts on the posts assigned to the same tags.

<?php $orig_post = $post;
global $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),
'posts_per_page'=>4, // Number of related posts that will be displayed.
'caller_get_posts'=>1,
'orderby'=>'rand' // Randomize the posts
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts" class="clear"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() ) { the_post_thumbnail(array(180,150)); } ?></a>

 <a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<? }
echo '</ul></div>';
} }
$post = $orig_post;
wp_reset_query(); ?>

Open you style.css file for enter CSS codes for related posts. You can also edit CSS code for change look of your related posts. Before insert this code in style.css file make sure there no other code with #related_posts class otherwise related posts not show well.

#related_posts {
margin:5px 0px 10px 0px;
}
#related_posts ul {
overflow:hidden;
margin:0;
}
#related_posts li {
list-style:none;
float:left;
margin:0 22px 0 0;
}
#related_posts li a {
display:block;
text-decoration:none;
letter-spacing:1px;
text-align:center;
width:180px;
line-height:16px;
border-bottom:none;
overflow:hidden;
}

#related_posts li img {
padding:5px;
background-color:#f4f4f4;
border:1px solid #ddd; }

#related_posts li img:hover {
background-color:#ddd;
}
#related_posts h3 {
border-top:1px solid #AAAAAA;
color:#135A9F;
padding:10px;
}

About Sibi Antony

Bootstrap and Android LOVER. I've been creating things for the web for over 10 years, from the period of flash and table based layout web sites till mobile and tab friendly web sites.
Posted in Wordpress

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.