How to create a WordPress Widget

WordPress widgets makes it easier for a user to simply add something on footer or side bar by drag and drop elements. Widgets generally comes with plugins and themes. But what if you want to create your own widget? In this post, I will show you how to create your own custom WordPress widget.

Before we start with the code part, you should know that there are two ways of creating the widget. You can either add the widget code directly in the functions.php file of the theme or you can create a site wide plugin for this. Adding code in functions.php will work, but this widget will only be available for the current theme. If you change the theme, you will have to copy the same widget code in the theme file. But creating a site wide plugin will have no effect of theme change. You widget will be theme independent.

You can decide what you want to do. So, first we will see how to create a site wide plugin. If you do not want to create site wide plugin and are comfortable with modifying functions.php file, you can skip this part.

Create site wide plugin

Step 1: For this, we will create a simple plugin for adding all our custom codes to the WordPress site. Follow these steps:

Step 2: Go to the plugins folder and create a new folder “myplugin”.

Step 3: In this new folder, create a new php file and save it as “myplugin.php” name.

Step 4: Now put this code in the file

 Step 5: Now activate this new plugin from WordPress Dashboard.

Create a WordPress Widget

Now we will see how to create a WordPress widget. If you can these codes to your site wider plugin or theme’s functions.php file.

To create a widget, you need to extend the standard WP_Widget class and its functions. So, the basic widget will look like this. Change the name of Widget and description as per your choice

This widget will look like this on adding to sidebar or footer.

Custome Widget

And it will look like this in available widget section

Custom Widget

 

In this widget, we have not given any output. So, adding this will have no effect on the website. If you want to show some output, use function widget().

Now we will create a plugin that will take user input. And this input will be show on the page where the widget will be added.

You can add or change fields as per your need. But the process will be the same. If you face any problem or if you have any query, you can ask via comments.

advertisement

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest updates, web design resources and tools.

You have Successfully Subscribed!

About The Author

    ADD YOUR COMMENT

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Receive fresh web design resources and SEO tips in your email by our weekly newsletter

You have Successfully Subscribed!