Related Post WordPress Without Plugin

When developing a WordPress post template, it’s common to need to display Related Posts at the end of an article or in the sidebar. This can be easily achieved without resorting to using plugins. You can accomplish this by simply incorporating the following code snippet into your function.php file:

add_shortcode( 'Related_posts', 'get_related_posts' );
function get_related_posts(){
	$categories = get_the_category();
	$category_id = $categories[0]->cat_ID;
	$post_id = get_the_ID();
	
	$args = array(
	'post_type' => 'post',
	'cat' => $category_id,
	'posts_per_page' => 3,
	'orderby' => 'date',
	'order' => 'DESC',
	'post__not_in' => array($post_id),
	'suppress_filters' => true
     );
    $loop = new WP_Query( $args );
	if ($loop) {
		$output = '';
		if ( $loop->have_posts() ) {
			$output = '<div class="related_posts">';
			$output .= '<ul>';
			while ( $loop->have_posts() ) : $loop->the_post();
				$output .= '<li class="item"><a href="'.get_permalink().'" target="_self">';
				$output .= '<div class="image">'.get_the_post_thumbnail( get_the_ID(), 'thumbnail' ).'</div>';
				//Or an option with the output of an image in the background format
				//$output .= '<div class="image" style="background-image: url('.get_the_post_thumbnail_url( null, 'thumbnail' ).')"></div>';
				$output .= '<div class="content">';
				$output .= '<h4 class="title">'.get_the_title() .'</h4>';
				$output .= '<div class="text">'.get_the_excerpt().'</div>';
				$output .= '</div>';
				$output .= '</a></li>';
			endwhile;
			$output .= '</ul>';
			$output .= '</div>';
		}
		wp_reset_postdata();
		echo $output;
	}
}

Next, we output the function in the post template – single.php:

<?php get_related_posts();?>

Alternatively, you can output related posts via the add_shortcode function by adding a shortcode in the editor:

[Related_posts]

The function first retrieves the categories associated with the current post using the get_the_category function, and then uses the cat_ID of the first category to query the database for related posts. The post_type parameter is set to post to only retrieve posts, and the posts_per_page parameter is set to 3 to limit the number of related posts displayed.

The function then uses the WP_Query class to retrieve the related posts, and displays them in an unordered list with an image, title, and excerpt for each post. The suppress_filters parameter is set to true to prevent the related posts from being filtered by other plugins or themes.

This function improves site navigation by suggesting relevant content to users based on the current post, enhancing engagement and potentially reducing bounce rates. By incorporating this code, you can create a more interactive and user-friendly experience for your visitors, guiding them to explore additional content that aligns with their interests.