This post describes how to show related posts and articles in a wordpress website or blog without installing any extra plugin. There are many plugins available for displaying related posts on a blog post or article page. Many webmasters and website owners don’t want to install any additional plugin. Find out here exact code for showing related articles based on categories and post tags.
Simply copy and paste this php code in single.php file of your current wordpress theme. Related Posts code for latest wordpress version. Find related posts code for wordpress version 3.1 to 3.9.1.
Show Related Posts by Post Categories
<?php $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'=>5, // Number of related posts that will be shown. 'ignore_sticky_posts'=>1 ); // Rest is the same as the previous code
Show Related Posts by Tags
<?php $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, // Number of related posts that will be shown. 'ignore_sticky_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>'; } } ?>
If you are using wordpres version below 3.1 and than replace “ignore_sticky_posts” in this code with “caller_get_posts”. Read this code change in detail at Class Reference/WP Query.