Function to add Related articles with thumbnails to your wordpress blog without a plugin

Displaying related articles below your wordpress posts can not only help with improved viewer engagement but also with better search engine crawling and on-site optimization.

There a variety of ways to fetch related posts that you want displayed. They can fetched based on related categories, tags or even article keywords. In this article, we will fetch the related articles from the categories of the main article.

We will first check all the categories that the main article is listed under and then display four random articles from these categories making sure that the current post is not displayed. The result will look as follows and will be displayed right at the end of your posts:

related-articles-with-thumbnail-2

You can increase or decrease the number of articles to display and adjust the styles and thumbnail sizes accordingly. For instance, if you want two articles to be displayed, you can increase the thumbnail and font sizes substantially.

Step 1: Login to your wordpress dashboard and go to Appearance > Editor and click on the functions.php link on the right panel.

Step 2: Add the following code to the end of your functions.php page:

/* Function to add related posts with thumb on single post pages */
function related_posts_with_thumb($content){
global $post;
if( is_single() ){
$rel_posts = '';

# 1. get category IDs of the current article and save to variable as an array.
$categories = get_the_category();
foreach($categories as $category){
	$rel_cat[] = $category->cat_ID;
}
# 2. arguments for wp_query.	
$rep_args = array(
	'post__not_in' => array($post->ID), # don't display current post.
	'category__in' => $rel_cat, # get posts within current categories.
	'posts_per_page' => 4, # number of posts to display.
	'orderby' => 'rand' # display random posts.
);
# 3. run the query.	
$rep_query = new wp_query($rep_args);

# 4. if the query has posts start the loop.
if($rep_query->have_posts()){
while($rep_query->have_posts()) : $rep_query->the_post();
	$rel_img = get_the_post_thumbnail($post->ID, 'thumbnail'); ## get featured image with default thumbnail size. 
	$rel_title =  get_the_title(); # get post title.
	$rel_link = get_permalink(); # get post link.	
	$rel_posts .= "<div id='content_rel_posts'> <a href='$rel_link'>$rel_img</a> <p><a href='$rel_link'> $rel_title </a></p></div>";
endwhile;
wp_reset_postdata();
}
# 5. Output.
$content .= "<h2 class='heading_rel_posts'>Related Articles</h2> $rel_posts";
}
return $content;
}
add_filter('the_content', 'related_posts_with_thumb', 2);

Step 3: Add the following to your style.css file.

The final step is to style the related articles section. To do this, add the following to your blog's style.css file. You can make changes to this style to align your article images and text properly in-case you change the thumbnail size. As the width is set in percentages and font size in em's this related posts section is fluid in nature. Or in other words, it will change automatically to fit the screen. You can make use of media queries to make this fully responsive.

/* div width, margins and float. */
#content_rel_posts{
	width:22%; /* width of each article column. */
	float:left;
	margin:5px 12px 5px 0;
	padding:0px;
}
/* style for article heading. */
#content_rel_posts p {
	font-size:0.9em;
	line-height:120%;
	padding:5px 0 0 0;
	margin:0px;
}
/* style for article heading link. */
#content_rel_posts a{
	text-decoration:none;
	color:#21759b;
}
/* style for thumbnail */
#content_rel_posts img{
	float:none;
	display:block;
	padding:0px;
	border-radius: 3px; 
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); 
	height: auto; /* Make images responsive. */
	max-width: 100%; /* Make images responsive. */
}
/* style for h2 heading tag */
h2.heading_rel_posts{
	padding:0px;
	margin:0px;
	font-size:1.4em;
	color:#666;
}

Code explanation

#1: We use get_the_category() function to get all category ID's of the current article and save it to the variable rel_cat as an array.

#2: We then set arguments for wp_query(), The first argument post__not_in ensures that the current post is not displayed as a related article. The final argument orderby is set to displays random posts. So each time the page loads, a random set of articles will be displayed. Other arguments include the categories to query, the number of posts to display which is set to 4.

#3 & #4: We then run the query and if the query has results, we get the thumbnail image of the post, post title and the post permalink, wrap it in div tags and append it to the variable $rel_posts.

#5: We then append the output to $content which contains all the content to the single post pages and return it as output. Finally, we add a filter to the_content() hook to display the output on the single post pages.

The only two things that you might want to edit in the code are the number of posts to display and the thumbnail size. Let's see how this can be done.

Changing number of related posts to display:

If you want to change the number of posts that are being displayed, change the value under the posts_per_page argument in point #2. Currently it is set to display 4 articles.

Changing thumbnail size:

In this code, the thumbnail size has been set using the keyword 'thumbnail' (see rel_image variable in point #4).

$rel_img = get_the_post_thumbnail($post_id, 'thumbnail'); 

The thumbnail keyword displays the thumbnail of the image as per the size set in your media settings. This is generally 150 x 150 pixels. To check or alter this size, you can go to your media settings (settings > Media) in your wordpress dashboard and alter size for the thumbnail option.

If you do resize your thumbnail size, make sure to install and run the regenerate thumbnails plugin so your images are resized to the new size.

If you do not want to mess around with the wordpress standard image sizes, you cause create your own custom image sizes using the add_image_size() function.

The add_image_size() function takes four parameters. The first parameter is the name that will be used to identify this new image size. The next two parameters are the image width and height. The final parameter defines if or not you want the image to be cropped. keep this to true as cropping produces the best results if you want to display even looking images.

For example, if you want to create and use a custom image size of 250 x 250 pixels you can add the following to your functions.php file.

add_image_size('rel_post_thumb', 250, 250, true );

Once added, run the regenerate thumbnails plugin by going to Tools > Regen. Thumbnails and clicking 'Regenerate All Thumbnails'. This will regenerate all your images with the new dimensions specified.

Note: If you want to regenerate only one or a few images instead of all images do this:

a.) Go to you media library (Media > Library).

b.) Make sure that the list view is selected so images are being displayed as a list and not as a grid. You can do this by clicking the 'list' icon at the top left corner next to the Filter button.

c.) Now check the check-boxes of images that you want to resize, hover over a image and click 'Regenerate Thumbnails'.

Once the images have been regenerated, you replace the keyword 'thumbnail' in the code with the name of the new image. In this case, rel_post_thumb.

Replace this line:

$rel_img = get_the_post_thumbnail($post_id, 'thumbnail'); 

With this:

$rel_img = get_the_post_thumbnail($post_id, 'rel_post_thumb'); 

Once you do this, your related posts will now use this new thumbnail size. You can then edit your style.css file to make sure that the images align properly. As a best practice, always use a child theme when making changes to your functions.php file. This way your changes will not be overwritten when your theme is updated.

References:
WordPress.org - get_the_category function reference.
WordPress.org - wp_query class reference.

 
 
 
 

Comments

  1. Kevin says:

    Really great tip!

    One question, how would you go about adding a default thumbnail image for posts without a featured image? The output is a bit wonky with no thumbnail.

  2. Jackson says:

    Thank You so much for this amazing article, I had searched a lot of how to do this on my website.

  3. Mike says:

    Hello,
    I’m a beginner in WorldPress. I’d like to show Related Posts. In the main menu I have Category A, and in Category A - Subcategories A, B and C. The posts are in Category A, but they can also be present in all 3 Subcategories. When choosing one of the Related Posts something goes wrong and the posts from the initially chosen Subcategory don’t show correct anymore.

  4. This is best solution I find and related posts through functions.php is excellent and thanks for this article.

  5. Tomas says:

    Hi,

    any idea on how to center the #content_rel_posts div? Because now it is aligned to the left side and there's a gap to the right side. On a desktop version, the gap is small, but on the mobile, you can fit another thumbnail in between.

    Thanks

Leave a Reply to Mohan Manohar Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.