Many people who operate websites with WordPress often want to add thumbnails to their “Recent Posts” section.
Unfortunately, as of February 2024, there isn’t an option to display thumbnail images in the “Recent Posts” widget.
But don’t worry, in this article, we will share how you can add thumbnails to recent posts by simply adding a few lines of code to the functions.php file.
Table of Contents
Add thumbnails to “Recent Posts”
Here is the PHP code to add thumbnail images to recent posts in WordPress.
Please put this in functions.php.
※If you’re uncomfortable with editing PHP files, we recommend using the “method with plugins” that will be introduced later.
// Add thumbnails to "Recent Posts"
function custom_recent_posts_title($title, $id){
if( preg_grep('/class-wp-widget-recent-posts.php/', array_column(debug_backtrace(), 'file')) ){
$thumb = get_the_post_thumbnail($id) ? : '<img src="'.get_template_directory_uri().'/lib/images/noimage.png">';
$title = "<figure>$thumb</figure><p>$title</p>";
}
return $title;
}
add_filter('the_title', 'custom_recent_posts_title', 10, 2);
Code outputting recent posts
The above code is a simple one that represents “When the_title (or get_the_title) function is called in class-wp-widget-recent-posts.php, append an img tag to the original title and return it.”
The class-wp-widget-recent-posts.php is located under /wp-includes/widgets/.
The files under wp-includes directory should not be directly rewritten, so using the add_filter function from the functions.php file is the appropriate method for making changes.
Styling with CSS for appearance adjustments
The final step is to adjust the appearance using CSS.
In this style example, we align the title and thumbnail side by side and add a border to the thumbnail.
.widget_recent_entries a{
display:flex;
gap: 0 4%;
}
.widget_recent_entries figure{
width: 38%;
height: 65px;
border: 2px solid #e3ddd7;
border-radius: 5px;
overflow: hidden;
}
.widget_recent_entries img{
width: 100%;
height: 100%;
object-fit: cover;
}
.widget_recent_entries p{
width:58%;
}
Method using a plugin
If you’re uncomfortable with editing PHP files, using a plugin might be a better option.
In WordPress, there seems to be a useful plugin that provides a ‘widget that outputs recent posts with thumbnails’ as shown below.
Recent Posts Widget With Thumbnails See How to use
Recent Posts Widget Extended See How to use
That is all, it was about how to add thumbnails to “Recent Posts” in WordPress!