Sometimes we need to show some related posts in our site. We can do this work two easy way. First, we will learn how to show related posts using tag. We click add new post or edit post and add tag and then update. Then we want to add another post and added some similar tag in this post and at last click update. You can use this code and must be added single.php template.
[source]
<?php
$cn_tags = wp_get_post_tags($post->ID);
if ($cn_tags) {
$tag_ids = array();
foreach($cn_tags as $cn_tag)
$tag_ids[] = $cn_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>’;
}else {
echo ‘<h3>No Related Posts</h3>’;
}
}
?>
[/source]
Second, we will learn how to show related posts using category. We click add new post or edit post and select category and then update. Then we select similar category in this post and at last click update. You can use below code.
[source]
<?php
global $post;
$categories_of_cn = get_the_category($post->ID);
if ($categories_of_cn) {
$category_ids = array();
foreach($categories_of_cn as $category_of_cn)
$category_ids[] = $category_of_cn->term_id;
$args=array(
‘category__in’ => $category_ids,
‘post__not_in’ => array($post->ID),
‘posts_per_page’=> 2, // No. of related posts what do you want to show.
‘caller_get_posts’=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo ‘<h3>Related Posts by category</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>’;
}else {
echo ‘<h3>No Related Posts</h3>’;
}
}
?>
[/source]
Second, we will learn how to show related posts using category. We click add new post or edit post and select category and then update. Then we select similar category in this post and at last click update. You can use below code.