Web Design that taps into the haromny and vision of your dreams.

How To Create Wordpress Widgets

Creating WordPress Widgets

Written By on in PHP

1,373 words, estimated reading time 7 minutes.

Wordpress Widgets are pieces of add-on code that extend the functionality of Wordpress, either behind-the-scenes or extra visual code. Widgets allow these code segments to be quickly and easily added to predefined sidebars on most themes.

Creating Your First Website Series
  1. What are the types of website available
  2. Introduction to Web Hosting
  3. Registering Domain Names and Configuration
  4. Installing Wordpress
  5. Setting Up New WordPress Site
  6. How To Install WordPress Themes and Plugins
  7. Using WordPress Custom Fields
  8. Creating WordPress Themes
  9. How To Create Wordpress Widgets
  10. 10 Essential WordPress Plugins for 2008
  11. WordPress Security 101

This article refers to old versions of Wordpress. For an up to date guide for the most recent versions (2.8+) please see this article - How To Create Widgets for WordPress 2.8

Before Wordpress version 2.0, these Wordpress Widgets had to be hand coded into the theme template, so knowledge of PHP was required. In version 2.0 they introduced "Widgets" which wrap around a plugin and allow a non-code editing method for incorporating into a theme using sidebars and a drag and drop interface.

This tutorial covers creating a Widget, creating a plugin widget, adding sidebars to a theme, and upgrading a non-widget plugin.

Creating a Simple Wordpress Plugin

You can use this as a code snippet for your projects. I am going to create a simple plugin that does nothing but display "Hello World". I'll leave the actual functionality of the plugin to you ;)

Create a new php file in your plugin directory called my-hello-world.php, and type the following plugin code:

<?php
/*
Plugin Name: Hello World
Plugin URI: http://timtrott.co.uk/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: http://timtrott.co.uk/
*/
 
function sampleHelloWorld() 
{
  echo "<h2>Hello World</h2>";
}
?>
 

The lines inside /* and */ are used by Wordpress to find out about the plugin. We have one function called sampleHelloWorld which does exactly that.

Now, traditionally we would have had to open up the sidebar of the theme you are using, find the location of where you want the Hello World displayed, and hard code the function in. Upload to the server and test. If for some reason there is a problem with your plugin (or a third party plugin) then your site would almost certainly stop working. Changing the location from the left to the right sidebar means editing both files accordingly. This isn't very good.

Widgets

Widgets take away the need for editing the sidebar files of a theme and allow for a drag and drop interface in the admin panel. Let's have a look at how we can widget enable our plugin.

Open up the Hello World plugin file again and add these lines:

 
function widget_myHelloWorld() {
?>
  <h2 class="widgettitle">My Widget Title</h2>
  <?php sampleHelloWorld(); ?>
<?php
}
 
function myHelloWorld_init()
{
  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');     
}
add_action("plugins_loaded", "myHelloWorld_init");
 

The first function here is what will be displayed on the sidebar when it's set-up correctly. Notice that we are calling on our old function. This is upgrading the existing plugin to be widget enabled. You can if you like replace the function call with the function statements and combine the two functions.

The second function is called by Wordpress when the plugin is activated. It calls a Wordpress function that will register a new widget which will be called "Hello World" which will call our new widget function.

Add action just tells Wordpress to call myHelloWorld_init when the plugin is loaded.

Enhancements for Theme Compatibility

While this widget will function fine, we can make some improvements to enable greater theme compatibility - not everyone uses the same themes as you test on.

Wordpress will pass parameters to your widget, which contain information about the sidebar and the CSS classes. We should process these parameters and output the correct tags, or you risk breaking some themes.

The first thing we need to do is change our sampleHelloWorld function so that it will accept parameters, then to process these parameters into variables. This is done using the extract function.

 
function widget_myHelloWorld($args) {
  extract($args);
?>
  <h2 class="widgettitle">My Widget Title</h2>
  <?php sampleHelloWorld(); ?>
<?php
}

These two lines will allow us to reference some variables and output correct HTML structure for the theme being used. The most important variables are before_widget, after_widget, before_title and after_title. Previously we have surrounded the widget title with a hard coded H2 tag with a CSS class widgettitle, but many themes do not support these tags. They may use a div, or an h1 or a span, so we need our widget to be flexible.

 
function widget_myHelloWorld($args) {
  extract($args);
  echo $before_widget;
  echo $before_title;?>My Widget Title<?php echo $after_title;
  sampleHelloWorld();
  echo $after_widget;
}

These changes will allow our plugin to use the same tags as the theme author informs us we need to use and will allow your widget to look the same as the other widgets in the sidebar.

To configure these options inside a theme, please see the section below on theme support.

Complete Plugin:

<?php
/*
Plugin Name: Hello World
Plugin URI: http://timtrott.co.uk/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: http://timtrott.co.uk/
*/
 
function sampleHelloWorld() 
{
  echo "<h2>Hello World</h2>";
}
 
function widget_myHelloWorld($args) {
  extract($args);
  echo $before_widget;
  echo $before_title;?>My Widget Title<?php echo $after_title;
  sampleHelloWorld();
  echo $after_widget;
}
 
function myHelloWorld_init()
{
  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');     
}
add_action("plugins_loaded", "myHelloWorld_init");
?>
 

Testing your Plugin

If you check your plugins page now, you should now have a new plugin listed called Hello World which you can activate. On the Presentation tab, select widgets, and you should see your new widget available to be dragged onto a sidebar. Save your changes and admire your new work.

Wordpress Widget listed as installed
Wordpress Widget listed as installed

Stop! My Theme Doesn't Support Widgets!

If your theme does not have widget enabled sidebars, this little tutorial will help make it widget enabled. I am using a very basic sidebar theme, most sidebars are a little more complex than this.

 
<div id="sidebar">
  <ul>
    <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
      <?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?><br/>
      <li><h2>Archives</h2>
        <ul>
          <?php wp_get_archives('type=monthly'); ?>
        </ul>
      </li>
      <?php wp_list_categories('show_count=1&title_li=<h2>Categories</h2>'); ?>
    <?php endif; ?>
  </ul>
</div>
 

The first of these lines does an if else statement, if we have a sidebar function call it otherwise we do the existing hard coded sidebar.

The second line (endif) tells the if statement where the hard coded sidebar ends. Anything between the first and second lines will be shown if widgets are disabled or no widgets are assigned to the sidebar.

Before you can add a widget to this sidebar, we need to make Wordpress aware of it by registering it.

Open, or create, functions.php in your theme folder, and find (or add) a line like this:

 
<?php
if ( function_exists('register_sidebars') )
    register_sidebars(1);
?>
 

Where the parameter to register_sidebars is the number of sidebars defined in your theme. You can have any number of sidebars. Now you will be able to add widgets to your sidebar.

Should you wish to configure the elements that will appear before and after a widget or the tags that a widget title will appear in, you can setup the options array and pass it to the register_sidebar function.

register_sidebar(array(
'before_widget' => '<li>',
'after_widget' => '</li>',
'before_title' => '<div class="sidebar_title">',
'after_title' => '</div>',
));

This will cause the widget to be contained within <li></li> tags and the widget title will be in a div with the CSS class sidebar_title.

As with most programming and development, there are a number of different methods of obtaining the same results, the techniques listed here are just what works for me.

You may also be interested in reading how to create control panels for your widgets.

Last updated on: Wednesday 21st June 2017

 

Comments
Andrew

Andrew

Thanks for tutorial! I never attempted to write a plugin before for a fear it would be too complicated.. Now I shall try! :)

Reply to Andrew
otenyano

otenyano

The plugin works. But I can only use the widget one time. How to make it usable on more sidebars?

Reply to otenyano
otenyano

otenyano

The plugin works. But I can only use the widget one time. How to make it usable on more sidebars?

Reply to otenyano
Alok Ranjan Dubey

Alok Ranjan Dubey

Thanks,I get a good knowledge about your right instruction.

Reply to Alok Ranjan Dubey
mahmud

mahmud

thanx for informative post. i am a newbie to php and do not follow the array, argument etc functions. Please write a tutorial on how to create a simple widget which i can place anywhere in my theme using div tag. Thanks in advance.

Reply to mahmud
alan

alan

Excellent! Thanks for this .. exactly what I was looking for!!

Reply to alan
Amitabha Roy

Amitabha Roy

The tutorial is small and best. I have learnt widget creation very quickly from here. Thanks.

Reply to Amitabha Roy
satish

satish

Awesome article.. thanks a lot.

Reply to satish
Raul Singh

Raul Singh

Thanks Buddy,
A very well written article. Cheers..keep the good work...

Reply to Raul Singh
Todd M.

Todd M.

Love this. Thank you for the info.

Reply to Todd M.
ibnu

ibnu

thanks, nice info...

i just learn create plugin that contain widget....

Reply to ibnu
Udar Gromov

Udar Gromov

2012-01-31 TUE 13:40
First time ever I am leaving a comment!
Because, this is a pure gold!
I was able to create my Plug-in in minutes.
This not only usable, by educational!
Especially valuable for me was Summary.

Fantastic! Thank you for your style of presenting!
As a courtesy to readers, I ran a spell check on my message.

Reply to Udar Gromov
Tim Love

Tim Love

This is an excellent article. As someone who has no programming skills, but loads of ideas for wordpress plugins; which is the best place for me to go to be able to hire someone with suitable skills to be able to do the programming for me?

Reply to Tim Love
Shaile

Shaile

Hi ,

Thanks to help us.
It's great and very easy way to make a wedget thanks a lot....:)

Reply to Shaile
Wingman

Wingman

Thank you very much for the post! Simple and clear! Just great!

Reply to Wingman
relisys

relisys

Tim Trott you are absolutely awesome! I have been trying to get this solution for 4 days straight and no one on irc or anywhere else could help me.

Many thanks !!!!! Thank you Thank you Thank you.!!

Reply to relisys
SAMsan

SAMsan

Awesomeness !

Reply to SAMsan
Steven Ferrino

Steven Ferrino

Thanks Tim, this just saved me a bunch of time.

Reply to Steven Ferrino
DavidM

DavidM

Thank you much. I'm working on a plugin right now using this base and hopefully will get it released very soon.

Reply to DavidM
Cairns Diver

Cairns Diver

Thanks for the tutorial, I was trying to find a way to convert mt plugin into a widget for the sidebar.

Reply to Cairns Diver
Chad Huntley

Chad Huntley

Thanks for this tutorial, it was very helpful in developing a new widget for BuddyPress!

Reply to Chad Huntley
IWM - Marketing Internet

IWM - Marketing Internet

Tim, with your help I created my first widget ever!

Thanks a lot man

Reply to IWM - Marketing Internet
Deep C

Deep C

Simple and Superb !!
Thanks.

Reply to Deep C
DesignMango

DesignMango

Nice tutorial thanks

Reply to DesignMango
Orion

Orion

I've followed the tutorial here, & while the widget appears in the plugins list (which I've activated), my activated plugin doesn't show in the Appearance->Widgets list.

Might you know why?

- O8

Reply to Orion
Towfiq I.

Towfiq I.

simple and awesome. Thank you so much for this post :D

Reply to Towfiq I.
Prasath

Prasath

Thank You very much!!!

Reply to Prasath
Leyton Jay

Leyton Jay

This is shockingly awesome.
Can't believe it was so easy, I would've started doing this years ago if I'd known!

Cheers mate.

Reply to Leyton Jay
purwa

purwa

wow great! ,this was exactly the solution I was looking for. Thanks alot!

Reply to purwa
Jeff

Jeff

Thank you very much for taking the time to create and share this. With the release of WP 3.0 I'm stepping more into the programing side of WP as I create a custom post type. This is a perfect tutorial for getting me started with Widgets as I wanted a way to display custom post type output in a widget. Thanks!

Reply to Jeff
Dhinakran

Dhinakran

Nice and smart for the plugin creators

Reply to Dhinakran
Y.Y.W.

Y.Y.W.

Great tutorial! Thanks for taking the time and post this article. I have bookmarked this post so I can always come back for reference.

Thanks!

Reply to Y.Y.W.
MySelf_v1

MySelf_v1

Is it possible to use JavaScript for the Widget?

Reply to MySelf_v1
cathy2005

cathy2005

Is it possible to add a widget programmatically so that the user does not have to Drag/Drop?

Reply to cathy2005
Clover

Clover

GEATE ! ! ! !

Getting this helpful suggestion, I could alive my PHP code as widgets.

Thank you!!!!

Reply to Clover
droid free apps

droid free apps

sweet, I have to create my own widget some a site am working on..

Reply to droid free apps
mona

mona

thank.It help me to make my plugin..

Reply to mona
Dan

Dan

Really impressive - very simple but very helpfull. Thanks!

Reply to Dan
djole

djole

Very useful article. I am ready to create my personal plugin.
Thank you.

Reply to djole
Glenn

Glenn

Tim,

Nice tutorial. After doing this over and over again I created to tool to take the tedium out of creating WordPress Widgets. Take a look over at http://www.widgetifyr.com and let me know what you think.

Glenn

Reply to Glenn
Conrad

Conrad

Really appreciate this tutorial. Nicely done - simple, quick and to the point. Nicely done.

Reply to Conrad
Angelika

Angelika

This was EXACTLY what I needed. Thank you.

Reply to Angelika
Neeraj Kumar

Neeraj Kumar

This is a very good example. Since I come from a C++ background, it helped e a lot.

Thanks again!

Reply to Neeraj Kumar
Pinyo

Pinyo

Really excellent tutorial. I appreciate it! Definitely cut my development time in half.

Reply to Pinyo
Christher Lenander

Christher Lenander

Thank you. This is what I been looking for. lots of articles about creating plugins but few about creating widgets.

Reply to Christher Lenander
Kaitora

Kaitora

Your plugin has been a great help for me to learn how to create some wordpress plugins. All of the other tutorials I have seen have not included anything on widgets. Thanks for the wonderful resource

Reply to Kaitora
jim smith

jim smith

Thanks for the hello world style example.
it was the best example i have found yet.

Reply to jim smith
KreCi

KreCi

Thanks man! That is so helpful! You will see my new widget plugin released soon!
Happy New year 2010! :)

Reply to KreCi
BrandonSch

BrandonSch

Great post , You've really hit the
nail on the head, I just don't understand why people quite get it.
I'm not for sure how many people I've talked to concerning this very
thing in the past month, and they just can't get it.

, Excellent post!

Reply to BrandonSch
Mauricio Wolff

Mauricio Wolff

Man... a lifesaver.

Thanks a lot. This tutorial and the plugin "TS Custom Widgets" (that allows me to select wich widget should show on each page/post) makes wordpress even better.

Tks a lot

Reply to Mauricio Wolff
Pravin

Pravin

@Uppfinnarn, @Stubbornella: The tags aren't mixed up. They are intented that way.

Instead of using echo $before_title . 'My Widget Title' . $after_title;

the author should have used
echo $before_title;?>My Widget Title<?php echo $after_title;

Reply to Pravin
Pravin

Pravin

@Uppfinnarn, @Stubbornella: The tags aren't mixed up. They are intented that way.

Instead of using echo $before_title . 'My Widget Title' . $after_title;

the author should have used
echo $before_title;?>My Widget Title<?php echo $after_title;

Reply to Pravin
Pravin

Pravin

@Uppfinnarn, @Stubbornella: The tags aren't mixed up. They are intented that way.

Instead of using echo $before_title . 'My Widget Title' . $after_title;

the author should have used
echo $before_title;?>My Widget Title<?php echo $after_title;

Reply to Pravin
Markus Freise

Markus Freise

Great tutorial to learn first steps. Thank you.

Reply to Markus Freise
Uppfinnarn

Uppfinnarn

There are <strong> tags in some of the latter examples; looks weird...

Reply to Uppfinnarn
Gopinath

Gopinath

Thank for your widget creation step by step explaination,its really awesome,,.

Reply to Gopinath
manitra

manitra

Hello,

Thanks for this tutorial, it's an excellent starting point.

Manitra.

Reply to manitra
chocobee

chocobee

thanks for the tutorial. do u know any link that teach how to create advance widget?

Reply to chocobee
Stubbornella

Stubbornella

There are a couple of places where the tag got mixed in with your php.

Reply to Stubbornella
jigar

jigar

really verry nice article for beginners and its working fine.... thanks ...

Reply to jigar
Vinicius

Vinicius

Greate tuto....

Tks

Reply to Vinicius
Christian

Christian

Great article/tutorial

How about writing about how to make options/settings for a widget. Thar would really be helpful...

Reply to Christian
kelik

kelik

Thanks..

Reply to kelik
Aod

Aod

I'm trying to create a sidebar widget using the code at http://www.stopie6.com/widgets.html (Simple Text Message), but can't work out which code to change in your example, and where to put the code in from the link? How would the php file handle that if statement?

Reply to Aod
Aod

Aod

I'm trying to create a sidebar widget using the code at http://www.stopie6.com/widgets.html (Simple Text Message), but can't work out which code to change in your example, and where to put the code in from the link? How would the php file handle that if statement?

Reply to Aod
Njualem

Njualem

Excellent and Cristal-Clear, I can now get into making widgets for my website.

Thanks a Million.

Reply to Njualem
Dimitar Stoyanov

Dimitar Stoyanov

Great article! Really good introduction to widget basics.

software_developer: thank for the nice link. Really helpful information about widget's setup!

Reply to Dimitar Stoyanov
seo free

seo free

Thanks really helpful to create a plugin for wordpress..thanks lot..:)

Reply to seo free
James

James

I just created a Google Translate widget for my blog and it only took a few minutes thanks to your introduction. Thanks!

Reply to James
Aakash

Aakash

Thanks very much. This is the thing i want !

Reply to Aakash
Jonathan Drain

Jonathan Drain

Great article! I found it very straightforward and helpful.

Reply to Jonathan Drain
Ian Kree

Ian Kree

Nice article. It tells exactly what I need to do.

Reply to Ian Kree
Abi

Abi

What a simple solution to my problem. I do not know php but is right away going to try this simple methid to make extra widgets for my blog.
Thanks!

Reply to Abi
gercek

gercek

better than wordpress documentation. thanks.

Reply to gercek
Davis

Davis

I dont get any of the mubble jummble! please help me in a simple way!!!

Reply to Davis
Phoenix

Phoenix

Hello sir, i have a question. How can i create a title field for the widget so the user can rename it with whatever they like. I really blind about php and Wordpress coding. So could you tell me the code and where to place it. Don't worry i can figure it out. Thanks:).

Reply to Phoenix
Björn

Björn

Thanx a lot for this nice tutorial ... !!!

Merry Christmas from Germany...

Reply to Björn
Jeff R.

Jeff R.

I am a little confused by this line;

&lt?php echo $after_title;

Is that supposed to be an actual less than bracket, making an opening php tag?

And, I thought when I started reading this that the Hello World example was just to show you the initial step. What is the purpose of it being called later in the function? I thought for an instant maybe we were supposed to put HTML in there, but you have the widget tags to use what the user theme has already...

Confused....

Reply to Jeff R.
Jeff R.

Jeff R.

I am a little confused by this line;

&lt?php echo $after_title;

Is that supposed to be an actual less than bracket, making an opening php tag?

And, I thought when I started reading this that the Hello World example was just to show you the initial step. What is the purpose of it being called later in the function? I thought for an instant maybe we were supposed to put HTML in there, but you have the widget tags to use what the user theme has already...

Confused....

Reply to Jeff R.
My Puppy654

My Puppy654

uhhh..... i don't get it! It looks to complicated! I thought it would be easy but i guess not..... i was planning on making a widget but now i guess not.... :(

Reply to My Puppy654
Rana

Rana

Very nice article. Thanks

Reply to Rana
stratosg

stratosg

excellent man! very very very helpful thanks!

Reply to stratosg
nkuttler

nkuttler

Great article, thanks! I've already written plugins but never before a widget. This and your post about how to create control panels for widgets are very useful.

Reply to nkuttler
Awshaal

Awshaal

Thank you so much, such wonderful article.. A++++

Reply to Awshaal

Really Nice guide to aadd widgets

Reply to
chat

chat

thanks for all..

Reply to chat
Fareeha

Fareeha

Thanks a bunch for the help.

Reply to Fareeha
palPalani

palPalani

thanks for you information, this is what i&squot;m looking for... great!

Reply to palPalani
McLarty

McLarty

Thanks for the great &quot;hello-world&quot; ...I&squot;m just getting started on a plugin!

got any good links to the next steps? Eg. Calling a flash movie or creating options inside of WordPress for the plug-in?

Reply to McLarty
don

don

Thx!! A nice and easy to follow explanation!

Reply to don

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me