Create Custom WordPress Recent Posts Widget

By Focusoncode January 25, 2019

Anyone using WordPress is aware that the default WordPress recent posts widget doesn’t include posts featured images. A lot of programmers simply install a plugin to achieve this feature. However there are programmers who don’t like to use plugins for small things.

In this article i will give you a step by step tutorial on how to create a custom WordPress recent posts widget with featured images and other data you may want.

Step 1: Locate default recent post widget and copy it

Find class-wp-widget-recent-posts.php file inside /wp-includes/widgets folder. This file contains the code for default recent posts widget.

Step 2: Include recent-posts.php file in functions.php

Copy this file, create a folder named classes inside your theme folder and paste this file inside. Now optionally rename the file as you wish (recent-posts.php)

In order for WordPress to run your code immediately you will need to include your file in functions.php inside your theme files.

Step 3: Start editing recent-posts.php

The first thing to do is to rename the class to My_Recent_Posts. Remember the class must be capitalized.

Next we need to modify __construct. In the photo below i have underlined with blue the codes we need to modify in order to avoid widget conflicts.

Next we will need to modify the code that displays in our website. The function widget contains all the code that displays recent posts in our website.

Find the list inside the widget function and edit it as you wish. This is the html that will be shown in your website when adding your recent posts widget.

I have simply included the featured image, but you can modify the whole html if you want.

That’s all about editing.

Step 4: Register our new widget

Now that we finished editing the recent posts widget, we need to register it in our function.php file.

Locate the function.php inside your template file and in the end of the file add the following code:

The above code registers the widget and after saving the file, your widget will be available in your WordPress widget section. Remember that My_Recent_Posts is the name of the class inside /classes/recent-posts.php file.

That’s all about creating a custom recent posts widget with featured images. Now you may use the new widget.

Leave a Comment

Your email address will not be published.