Display Related Posts on WordPress Blogs without using any Plugin

Showing related posts on your WordPress blog not only creates an easy to navigate interface for your blog visitors but also it influences SEO values in a positive manner. There are a handful of WordPress related posts plugin available for WordPress blogs to customize and show related posts at the bottom of your post. Customization may lead to the number of related posts, accuracy level, tag and category emphasis, placement location etc. However we can display related posts on WordPress blogs without using any plugins.

We will be using some simple PHP codes to filter similar posts by matching either tags or categories. If you want to display related posts by matching the post tags, you need to copy the below code and add the same to single.php template.

<?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.
‘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>’;
}
}
?>

Now if you want to display related posts by matching the post category, you need to add the following code in stead of the above one :


<?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.
‘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>’;
}
}
?>

TIP : Remember to take backup of your theme files before making any edit on them.

We will send you some more information related to Display Related Posts on WordPress Blogs without using any Plugin

Below are some more related articles to the topic:

Add Related Posts Widget in Blogger / Blogspot Blogs
Import Blogger Posts, Comments, Labels from Blogspot to WordPress
Doing WordPress SEO? Try HeadSpace2 SEO Plugin
Top 5 Twitter Plugins to Update your Tweets on WordPress Blogs
How To Create an Archive Page for Your WordPress Blog

Tags:

No comments yet.

Leave a Reply