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.

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.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

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 ) {
			setup_postdata( $related_post );
			echo '<div class="related-post">';
			echo '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">';
			if ( has_post_thumbnail() ) {
				echo '<img src="' . esc_url( get_the_post_thumbnail_url( $related_post->ID, 'medium' ) ) . '" alt="' . esc_attr( get_the_title() ) . '">';
			}
			echo '<h3>' . esc_html( get_the_title() ) . '</h3>';
			echo '<p>' . esc_html( get_the_content() ) . '</p>';
			echo '</a>';
			echo '</div>';
		}
		echo '</div>';
		wp_reset_postdata();
	}
}

Code language: PHP (php)

Explanation:

  • The custom_related_posts function is designed to generate and display related posts based on categories or tags. It can be used in WordPress template files, such as single.php or custom template files, to show related content to the current post.
  • The function starts by retrieving the post ID of the current post using get_the_ID().
  • Next, it retrieves the categories and tags associated with the current post using get_the_category($post_id) and get_the_tags($post_id) respectively. This allows the function to identify related posts based on these taxonomies.
  • An empty array called $related_posts is initialized to store the related posts that will be fetched.
  • If there are categories or tags available, the function sets up a query using get_posts($args) to fetch related posts. The query is constructed based on the following parameters:
    • post__not_in: Excludes the current post from the related posts list.
    • posts_per_page: Limits the number of related posts to be fetched (set to 3 in this case).
    • orderby: Specifies the order in which the related posts should be retrieved (in this case, randomly).
  • Inside the foreach loop that iterates through the $related_posts array, the post data for each related post is set up using setup_postdata($related_post). This ensures that the WordPress template functions like get_permalink(), get_the_title(), and get_the_content() retrieve the correct data for each related post.
  • Within the loop, the related post’s information is echoed, including the post’s title, content, and optionally, the featured image thumbnail. The echoed content is wrapped in appropriate HTML markup and CSS classes to suit the desired layout and styling.
  • After the loop, wp_reset_postdata() is called to restore the global post data to its original state, ensuring compatibility with other post-related functions used elsewhere on the page.
  • The related posts container is closed with the closing div tag.
  • By following these steps, the custom_related_posts function fetches and displays related posts based on categories or tags associated with the current post.

Please note that you may need to adjust the HTML structure and CSS classes according to your specific design requirements.

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 โ˜•๏ธ or donating via PayPal ๐Ÿ’ฐ.

More free knowledge, because why not?

Your thoughts matter, leave a reply ๐Ÿ’ฌ

Your email address will not be published. Required fields are marked *