How to Add Related Posts to Your WordPress Site Without Plugins – A Simple Guide
If you want to keep your readers engaged and interested in your content, one way to do it is by showing them related posts. Luckily, WordPress has a built-in function called get_posts()
that can help you fetch related posts based on the current post’s categories and tags.
Before making any changes to your WordPress theme, it’s always recommended to use a child theme. This ensures that any changes you make won’t be lost when you update your theme.
In this tutorial, we’ll show you how to use a custom function called custom_related_posts()
that will use the get_posts()
function to fetch related posts and display them in a nice, responsive grid.
Related Posts PHP Function
To use the custom_related_posts()
function, you need to include it in your functions.php
file. Here’s the code:
function custom_related_posts() {
// Get the post ID.
$post_id = get_the_ID();
// Get the categories.
$categories = get_the_category( $post_id );
// Get the tags.
$tags = get_the_tags( $post_id );
// Initialize an empty array for the related posts.
$related_posts = array();
// If there are categories or tags, get related posts based on them.
if ( $categories || $tags ) {
// Set up the query arguments.
$args = array(
'post__not_in' => array( $post_id ),
'posts_per_page' => 3,
'orderby' => 'rand',
);
// If there are categories, add them to the query.
if ( $categories ) {
$category_ids = array();
foreach ( $categories as $category ) {
$category_ids[] = $category->term_id;
}
$args['category__in'] = $category_ids;
}
// If there are tags, add them to the query.
if ( $tags ) {
$tag_ids = array();
foreach ( $tags as $tag ) {
$tag_ids[] = $tag->term_id;
}
$args['tag__in'] = $tag_ids;
}
// Get the related posts.
$related_posts = get_posts( $args );
}
// If there are no related posts based on categories or tags, get random posts.
if ( empty( $related_posts ) ) {
// Set up the query arguments.
$args = array(
'post__not_in' => array( $post_id ),
'posts_per_page' => 3,
'orderby' => 'rand',
);
// Get the random posts.
$related_posts = get_posts( $args );
}
// Output the related posts.
if ( ! empty( $related_posts ) ) {
echo '<div class="related-posts">';
foreach ( $related_posts as $related_post ) {
echo '<div class="related-post">';
echo '<a href="' . esc_url( get_permalink( $related_post->ID ) ) . '" rel="bookmark">';
if ( has_post_thumbnail( $related_post->ID ) ) {
echo '<img src="' . esc_url( get_the_post_thumbnail_url( $related_post->ID, 'medium' ) ) . '" alt="' . esc_attr( get_the_title( $related_post->ID ) ) . '">';
}
echo '<h3>' . esc_html( get_the_title( $related_post->ID ) ) . '</h3>';
echo '</a>';
echo '</div>';
}
echo '</div>';
}
}
Code language: PHP (php)
This function will get the current post’s categories and tags, and then use the get_posts()
function to fetch related posts based on those categories and tags. If there are no related posts based on categories or tags, it will fetch random posts.
Related Posts CSS Styles
To make the related posts look nice and responsive, we’ll use some CSS. Here’s the code:
.related-posts {
display: flex;
flex-wrap: wrap;
max-width: 1000px;
margin: 0 auto;
}
.related-post {
flex-basis: calc(33.33% - 20px);
margin: 10px;
}
.related-post img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
Code language: CSS (css)
This CSS code will display the related posts in a flexbox grid with 3 columns. Each related post will take up one third of the grid, and will have a margin of 10px. The images in the related posts will be resized to fit their container, and will be centered horizontally and vertically.
Using custom_related_posts() function
To use the custom_related_posts()
function on your single.php
file, you need to call it inside the loop.
if ( function_exists( 'custom_related_posts' ) ) {
custom_related_posts();
}
Code language: PHP (php)
Here’s a basic example of single.php
:
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
if ( function_exists( 'custom_related_posts' ) ) {
custom_related_posts(); }
};
};
Code language: PHP (php)
By utilizing the custom_related_posts()
function on your WordPress site, you can quickly fetch and present related posts to your audience. This feature can keep your readers engaged, and they may spend more time on your website, decreasing your bounce rate and increasing your pageviews.
Furthermore, the function_exists() function is used to verify if the custom_related_posts()
function is available before displaying the related posts at the end of your content. It ensures that your site’s functionality remains unaffected in case the function is not available.
Overall, implementing related posts on your WordPress site is simple and straightforward using the custom_related_posts()
function. It can enhance the user experience of your site visitors and boost your site’s engagement metrics.
Leave your feedback and help us improve 🐶
We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee ☕️.
Thank you for your feedback and support!
Your thoughts matter, leave a reply 💬