In this tutorial of WordPress Widget we will walk through how to create a custom widget for WordPress that enables you to display recent posts for custom post types.

Create the basic WordPress Widget

Create a folder name widgets inside your WordPress theme. In your activity.php file, write the following code:
WordPress Widget

The above code sets up our widget class. It’s extending an already built class – called WP_Widget, which have methods that we need to override. These methods are: update(), form() and widget(). It’s is just the rules for creating widgets.

Now, notice above that we have a method __construct() – which just register’s our widget id, a name and a description. We override another method update() – which just makes ensures that we’re passing the right values to our $instance array (also makes sure we’re using the correct calculated instance).

So all we need to create is 2 more methods: form() and widget(). Let’s take care of that next.

The form() method

The method form() builds the form that we have in the admin section. A text field for the Widget title, and a drop down list for the number of listings we want to show. In your activity.php file, write the following code:WordPress Widget

The widget() method

This is the method that actually outputs our widget. This method accepts a couple of arguments – one of them is our $instance array. In your activity.php file, write the following code:WordPress Widget

Pull our Custom Posts

This method will do a query of our custom posts. It will only return the number of posts that we’ve saved in our widget. Add this code to your class:WordPress Widget

Create a file named widgets.php inside the widgets folder, paste the following code:
WordPress Widget

In file named functions.php inside the theme folder, edit it, and paste the following code:
WordPress Widget

After adding the script login to your admin dashboard and navigate to Appearance >> Widgets and here you will find a new Widget has been created for your respective Custom Post TypesWordPress Widget

now drag the widget and drop onto your respective sidebar WordPress Widget

Leave a Reply

Or

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


CAPTCHA Image
Reload Image

Find us on Facebook

Subscribe to our Newsletter