Related posts could play a key role to boost your page views and reduce bounce rate. So here we will display the related posts in WordPress without a plugin for the sidebar. Are you excited to do this? Let’s just jump into it.
An Ideal Place to Add Code in WordPress
Most Important: Add the following code to your child theme’s functions.php file. If you add custom code directly to your parent theme’s functions.php file then it will be wiped entirely when you update the theme.
If you are using a custom theme and if it doesn’t require any update then you can directly place the code into wp-content/themes/your-theme/function.php file
Please also note that our team has tested all codes in WordPress 5.4 version with the GeneratePress child theme & Storefront child theme.
01 Get Related Posts by Category
So here we will create a shortcode "[tf_related_posts]"
which then can be added anywhere you like.
/*@ Get Related Posts */
if ( ! function_exists( 'tf_get_related_posts' ) ) {
function tf_get_related_posts() {
ob_start();
$id = get_the_ID();
/*@ Get current post's categories */
$categories = get_the_category($id); // Disabled this if you want tag wise posts
/*@ Get current post's Tags */
// $categories = wp_get_post_tags($id); // Enable this for tags wise related posts
if (!empty($categories)) :
/*@ Pluck all categories Ids */
$categories_ids = array_column( $categories, 'term_id' );
$related_args = [
'post_status' => 'publish',
'category__in' => $categories_ids, // Disabled this if you want tag wise posts
//'tag__in' => $categories_ids, // Enable this for tag wise related posts
'post__not_in' => [ $id ], // Exclude Current Post
'posts_per_page' => 5, // Number of related posts to show
'ignore_sticky_posts' => 1
];
$get_posts = new WP_Query( $related_args );
if ( $get_posts->have_posts() ) :
echo '<ul class="related_posts_list">';
while ( $get_posts->have_posts() ) : $get_posts->the_post();
echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
endwhile;
echo '</ul>';
endif;
endif;
return ob_get_clean();
}
add_shortcode('tf_related_posts', 'tf_get_related_posts');
}
The above code will find out the current Post ID
and get all categories associated with it. After that, we plucked the IDs of all categories. All those categories IDs passed in "category__in"
argument. Then, we are fetching posts with the help of WP_Query() function.
Currently, We are showing 5 related posts, so if you want to show more or fewer posts then you need to change the 'posts_per_page' => 5,
argument.
Now, It’s time to add some CSS as below. Please note that the look will vary as per your theme. You might need to add/change some CSS as per your requirement.
.related_posts_list ul {
list-style: none;
}
.related_posts_list li {
padding: 8px 14px;
font-weight: 500;
background: #fff;
margin: 5px;
border-radius: 5px;
transition: all .2s;
box-shadow: 0 2px 2px #d8e2f3;
}
.related_posts_list li a {
text-decoration: none!important;
}
.related_posts_list li:hover {
box-shadow: 0 3px 5px #d8e2f3;
transform: translateY(-2px);
}
That’s it. Now, just place the shortcode [tf_related_posts]
in your sidebar widget, ideally in a Text widget or HTML Widget, for that go to Appereance -> Customize -> Widget -> Sidebar
and then click on Add Widget button and select Text widget and place our shortcode and enjoy it.
02 Get Related Posts by Tags
We have already placed the code in a comment on above the example, If you want to enable related posts Tag wise, then you need to disable the Category wise code and enable Tag wise code.
You just need to comment or replace this $categories = get_the_category($id);
to $categories = wp_get_post_tags($id);
and this 'category__in' => $categories_ids,
to 'tag__in' => $categories_ids,
on the above example. After that, your code should look like below.
/*@ Get Related Posts by Tags */
if ( ! function_exists( 'tf_get_related_posts' ) ) {
function tf_get_related_posts() {
ob_start();
$id = get_the_ID();
/*@ Get current post's categories */
//$categories = get_the_category($id); // Disabled this if you want tag wise posts
/*@ Get current post's Tags */
$categories = wp_get_post_tags($id); // Enable this for tags wise related posts
if (!empty($categories)) :
/*@ Pluck all categories Ids */
$categories_ids = array_column( $categories, 'term_id' );
$related_args = [
'post_status' => 'publish',
//'category__in' => $categories_ids, // Disabled this if you want tag wise posts
'tag__in' => $categories_ids, // Enable this for tag wise related posts
'post__not_in' => [ $id ], // Exclude Current Post
'posts_per_page' => 5, // Number of related posts to show
'ignore_sticky_posts' => 1
];
$get_posts = new WP_Query( $related_args );
if ( $get_posts->have_posts() ) :
echo '<ul class="related_posts_list">';
while ( $get_posts->have_posts() ) : $get_posts->the_post();
echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
endwhile;
echo '</ul>';
endif;
endif;
return ob_get_clean();
}
add_shortcode('tf_related_posts', 'tf_get_related_posts');
}
On the above example, We have used wp_get_post_tags()
function to fetch all the tags related to the current post, then we plucked the tags IDs and passed those IDs to tag__in
argument, tag___in
will find out the posts related to the current post’s tags. We hope you understood this. Let’s see some further topics.
03 Add Related Posts in a Custom Post Type by a Taxonomy
Up till now, We have seen the related posts by category & tags, but what about a Custom Post Type taxonomy. It’s not that much harder. So to display related posts in a Custom Post Type, we will create another shortcode "tf_cpt_related_posts"
.
/*@ Get Related Posts for Custom Post Type */
if ( ! function_exists( 'tf_get_related_posts_for_cpt' ) ) {
function tf_get_related_posts_for_cpt() {
ob_start();
$id = get_the_ID();
/*@ Get current post's Taxonomy */
$taxonomy_terms = wp_get_post_terms($id, 'glossary'); // Replace your taxonomy name
if (!empty($taxonomy_terms)) :
/*@ Pluck all terms Ids */
$terms_ids = array_column( $taxonomy_terms, 'term_id' );
$related_args = [
'post_type' => 'source-book', // Replace your post type name
'tax_query' => [
[
'taxonomy' => 'glossary', // Replace your taxonomy name
'field' => 'id',
'terms' => $terms_ids,
'operator' => 'IN' // Options : 'AND' or 'NOT IN'
]],
'post_status' => 'publish',
'post__not_in' => [ $id ], // Exclude Current Post
'posts_per_page' => 5, // Number of related posts to show
'ignore_sticky_posts' => 1
];
$get_posts = new WP_Query( $related_args );
if ( $get_posts->have_posts() ) :
echo '<ul class="related_posts_list">';
while ( $get_posts->have_posts() ) : $get_posts->the_post();
echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
endwhile;
echo '</ul>';
endif;
endif;
return ob_get_clean();
}
add_shortcode('tf_cpt_related_posts', 'tf_get_related_posts_for_cpt');
}
On the above example, We have used wp_get_post_terms()
function to fetch all the taxonomies related to the current post, then we plucked the taxonomies IDs and passed those IDs to tax_query
argument.
In order to make the above example work, you need to change the taxonomy “glossary” at two places 1) 'taxonomy' => 'glossary'
2) $taxonomy_terms = wp_get_post_terms($id, 'glossary');
to your and change the 'post_type' => 'source-book'
to your own, We hope you understood this. Let’s see some further topics.
04 Automate Related Posts by Category or CPT’s Taxonomy
We can show the related posts easily based on the condition to automate it. So if we are on default posts, then it will show the related posts based on the Categories and if we are on Custom Post Type posts, then it will show the related posts based on Taxonomy.
This example is just a mixture of the above code with some additional conditions. Here we will create a shortcode "[tf_related_posts]".
Are you ready to do that? Let’s go then.
/*@ Get Related Posts */
if ( ! function_exists( 'tf_get_related_posts' ) ) {
function tf_get_related_posts() {
ob_start();
$id = get_the_ID();
/*@ Get current post's categories */
$categories = get_the_category($id);
if ( get_post_type() === 'source-book' ) :
$categories = wp_get_post_terms($id, 'glossary'); // Replace your CPT Taxonomy
endif;
if ( !empty($categories) ) :
/*@ Pluck all categories Ids */
$categories_ids = array_column( $categories, 'term_id' );
$related_args = [
'post_status' => 'publish',
'category__in' => $categories_ids,
'post__not_in' => [ $id ], // Exclude Current Post
'posts_per_page' => 5, // Number of related posts to show
'ignore_sticky_posts' => 1
];
/*@ Show CPT related posts */
if ( get_post_type() === 'source-book' ) : // Replace your post type
unset($related_args['category__in']);
$related_args['post_type'] = 'source-book'; // Replace your post type
$related_args['tax_query'] = [[
'taxonomy' => 'glossary', // Replace your CPT taxonomy name
'field' => 'id',
'terms' => $categories_ids,
'operator' => 'IN' // Options : 'AND' or 'NOT IN'
]];
endif;
$get_posts = new WP_Query( $related_args );
if ( $get_posts->have_posts() ) :
echo '<ul class="related_posts_list">';
while ( $get_posts->have_posts() ) : $get_posts->the_post();
echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
endwhile;
echo '</ul>';
endif;
endif;
return ob_get_clean();
}
add_shortcode('related_posts', 'tf_get_related_posts');
}
In order to make the above example work, You need to change the taxonomy and Custom Post Type name as we have shown in point 03.
We have added comments in the code wherever replacement requirement from your side so it will easy for you to replace the names. Please test all the examples one by one because all the above examples have the same function name so only first will execute.
Additionally, check out our guide: Add Related Posts in WordPress Without Plugin
That’s it for now. We hope this article helped you to add related posts in WordPress without a plugin.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂