Home » Labs » How to Show WordPress Related Posts without a Plugin  

How to Show WordPress Related Posts without a Plugin


Filed under Labs

Here is a good code which allows you to display related posts from WordPress tags. For example if you have posts with tags like mobile phones, Samsung and Lg then the below code will compare and display posts which have at least one similar tag.It is very useful in a WordPress theme development because we want to keep visitors within the site and increase page views. So just copy the bellow snippet into your WordPress template where you want to show related posts, it is better to show related posts just below current post. Have a nice blogging…

<?php
// Snippet for displaying related posts in WordPress using Tags
$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'=>5, // You can set the number as you like to display
		'caller_get_posts'=>1
	);
	$my_query = new wp_query($args);
	if( $my_query->have_posts() ) {
		echo '<h3>Related Posts</h3><ul>';
		while ($my_query->have_posts()) {
			$my_query->the_post();
		?>
			<li>
			<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
			<?php the_title(); ?></a>
			</li>
		<?php
		}
		echo '</ul>';
	}
}
?>

Posts you may like: