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:
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:
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:
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:
Create a file named widgets.php inside the widgets folder, paste the following code:
In file named functions.php inside the theme folder, edit it, and paste the following code:
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 Types
now drag the widget and drop onto your respective sidebar