Instead of using any plugin to show related posts based on the category, you can use this small piece of code to show post related to the category of the current post.
Also i will show how to first look for related post based on the tags you mentioned for the post. If there is no post based on the tags, then it will look for post related to the category.
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 '<h2>Related Posts</h2>';
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
else{
$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 '<h2>Related Posts</h2><ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
}
Keep checking for more tips n tricks
May 31, 2011 at 11:45 am
I couldn’t get this to work, is there something missing from it?
May 31, 2011 at 5:05 pm
Hey jaffa, everything here seems right as this is tried and tested code. Can you please tell me what error you get. Also, try this code for only categories and let me know.