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

How To Create WordPress Widgets with Control Panels

How to Create WordPress Widgets

By on in Coding

1,712 words, estimated reading time 8 minutes.

It is more than likely that your Wordpress Widget will need to have some user configurable settings, so why not include settings form within your widget?

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

These settings pages (admin panels, configuration screen and so on...) are accessed from within the Presentation » Widgets screen from Wordpress 2 and from Design » Widgets in Wordpress 2.5. When you add a widget to a sidebar, you may notice a little icon on the right-hand side of the widget. Clicking on this will open up the widget admin panel where your users can customise your widget to their needs.

How To Create Widgets with Control Panels
How To Create Widgets with Control Panels

Let's use the code from the Hello World widget of the last tutorial and change it around so that we have a settings page. We will see how to create the settings page, how to store/save and retrieve/load settings using the Wordpress database and how to handle user inputs.

<?php
/*
Plugin Name: Hello World
Plugin URI: https://timtrott.co.uk
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: https://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");
?>
 

The first thing we are going to create is the icon on the Widget sidebar screen, and get it to open up a blank screen which we will later fill with input controls.

We need to create a function that will be used to display and process the options. The convention is to use the plugin name appended with _control for the control panel page.

function myHelloWorld_control() 
{
}

We will come back to this function a bit later on. For now, we will just get Wordpress to use our blank form.

In the _init function where we register the sidebar widget, we need to add another function call that will tell Wordpress that we have a control panel associated with our plugin.

function myHelloWorld_init()
{
  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');
  register_widget_control(   'Hello World', 'myHelloWorld_control', 300, 200 );
}
 

This extra function specifies the title of the page, the function that will be called (in this example it does nothing yet) and the widget control panel screen will be 300 pixels wide by 200 pixels tall. You can test this now, or continue and add some content.

Wordpress Options

Before we get started on the admin panel, let's first have a look at how we can use the Wordpress options database to store values. Wordpress has a nice function that will do all the hard work for you called update_option. This function simply takes a key name and the data to store under that key, be it a string, integer or an array. You should try and use a unique, but meaningful, key name to avoid conflicts with other plugins or Wordpress itself. I also use a prefix of "widget_" to identify that the settings are for a widget.

The Wordpress options database is a table called by default wp_options, and maintains a list of key name and value pairs.

update_options("widget_myHelloWorld", "This is a test");
 

This will update the key named widget_myHelloWorld in the Wordpress database and set the value to "This is a test". You can retrieve the information at a later date using the get_option function. This function only takes one parameter - the key name to retrieve.

$title = get_option("widget_myHelloWorld");
echo $title;
 

In this example, we would expect to see "This is a test" on the screen.

Constructing our Admin Page

I am going to create the admin panel in four stages in this tutorial, you may wish to merge these all into one, or do them in a different order - it's entirely up to you.

1. Create the Form Controls

To begin with, you are going to need a form design. In this example, we are going to simply use a textbox and a label. I'll leave the form design to you!

Each line on the form should be contained within a paragraph block to keep a nice uniform spacing between all elements. By default, the items will be centred on the form, so if you need them to be left or right aligned, you will need to specify this in the p tag.

This is the code for my simple HTML form. You must use a unique name and id attributes on the form. You will notice that there is no

element in the code. This is because a form element is provided by Wordpress which encompass all the widgets that have been loaded.

function myHelloWorld_control() 
{
?>
  <p>
    <label for="myHelloWorld-WidgetTitle">Widget Title: </label>
    <input type="text" id="myHelloWorld-WidgetTitle" name="myHelloWorld-WidgetTitle" value="" />
  </p>
<?php
}
 

If you test now you should have a label and text box centred on the widget control form. It is more than likely that you will need more than one form control; however, I will let you work on that now you have a grasp of the basics.

2. Get Existing Data and Default Values

The next stage it to populate the form controls with either default values, or values obtained from the database with the get_options function.

Let's get the data from the database, perform a test on it to see if we have valid data, fill the data with default values if necessary then populate the form controls.

function myHelloWorld_control() 
{
  $options = get_option("widget_myHelloWorld");
  if (!is_array( $options ))
{
$options = array(
      'title' => 'My Widget Title'
      ); 
  }
 
?>
  <p>
    <label for="myHelloWorld-WidgetTitle">Widget Title: </label>
    <input type="text" id="myHelloWorld-WidgetTitle" name="myHelloWorld-WidgetTitle" value="<?php echo $options['title'];?>" />
  </p>
<?php
}
 

The first new line in this code will get the previously stored values from the database. We then test the output variable to see if it is null (no data was retrieved from the database) and if it is we create a new array with one element for the widget title. This method will guarantee that we have a valid value for the title (or another setting) from the database or a default value. We can then use the title stored in the array to output into the text box value attribute.

3. Get User Input and Store the New Settings

We need some way of capturing the value a user may type in the box and storing it in the database to be re-used. For this, we will need another form element that will identify our data when it is submitted. This new element is a hidden value which we will test against.

function myHelloWorld_control() 
{
  $options = get_option("widget_myHelloWorld");
  if (!is_array( $options ))
{
$options = array(
      'title' => 'My Widget Title'
      ); 
  }     
 
  if ($_POST['myHelloWorld-Submit']) 
  {
    $options['title'] = htmlspecialchars($_POST['myHelloWorld-WidgetTitle']);
    update_option("widget_myHelloWorld", $options);
  }
 
?>
  <p>
    <label for="myHelloWorld-WidgetTitle">Widget Title: </label>
    <input type="text" id="myHelloWorld-WidgetTitle" name="myHelloWorld-WidgetTitle" value="<?php echo $options['title'];?>" />
    <input type="hidden" id="myHelloWorld-Submit" name="myHelloWorld-Submit" value="1" />
  </p>
<?php
}
 

In this new code segment, we look at the PHP POST variable for an element called myHelloWorld-Submit (the same as the hidden field) and if we found it we extract the widget title from the post variable. It is important to ensure that the code we are about to insert into the database does not contain any malicious code, so we can use the HTML special chars function to help prevent SQL injections. We then make a call to update_option to save the new values to the database.

4. Using the Data

What is the point of doing all this and not using the data? None what so ever. Using the data within the widget is just as easy (in fact it's the same) as using the data on the form.

In our code that outputs the widget title, you simply need to get the values for the database with get_option, make sure we have valid information and then output the value. We have already seen this in action on the widget control stage, so I will just go straight to the full code listing for this tutorial.

Complete Code

<?php
/*
Plugin Name: Hello World
Plugin URI: https://timtrott.co.uk
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 2
Author URI: https://timtrott.co.uk
*/
 
function sampleHelloWorld() 
{
  echo "<h2>Hello World</h2>";
}
 
function widget_myHelloWorld($args) {
  extract($args);
 
  $options = get_option("widget_myHelloWorld");
  if (!is_array( $options ))
{
$options = array(
      'title' => 'My Widget Title'
      ); 
  }      
 
  echo $before_widget;
    echo $before_title;
      echo $options['title'];
    echo $after_title;
 
    //Our Widget Content
    sampleHelloWorld();
  echo $after_widget;
}
 
function myHelloWorld_control() 
{
  $options = get_option("widget_myHelloWorld");
  if (!is_array( $options ))
{
$options = array(
      'title' => 'My Widget Title'
      ); 
  }     
 
  if ($_POST['myHelloWorld-Submit']) 
  {
    $options['title'] = htmlspecialchars($_POST['myHelloWorld-WidgetTitle']);
    update_option("widget_myHelloWorld", $options);
  }
 
?>
  <p>
    <label for="myHelloWorld-WidgetTitle">Widget Title: </label>
    <input type="text" id="myHelloWorld-WidgetTitle" name="myHelloWorld-WidgetTitle" value="<?php echo $options['title'];?>" />
    <input type="hidden" id="myHelloWorld-Submit" name="myHelloWorld-Submit" value="1" />
  </p>
<?php
}
 
function myHelloWorld_init()
{
  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');
  register_widget_control(   'Hello World', 'myHelloWorld_control', 300, 200 );     
}
add_action("plugins_loaded", "myHelloWorld_init");
?>
 

Last updated on: Wednesday 27th June 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

mononelo

mononelo

Hi,
first of all, congratulations for this article and for the blog in general. Secondly I have a problem: I've created a plugin but I can't put it in different sidebars, it only serves for one sidebar. How could I modify this code to put my widget in multiple sidebars?
Thanks a lot!

Reply to mononelo
Tim Trott

Tim Trott

mononelo,

This article was written for an old version of Wordpress. If you have Wordpress 2.8 or above you can use the new Widget API which supports multiple sidebars out of the box. Tutorial here: https://timtrott.co.uk/creating-widgets-wordpress/

Reply to Tim Trott
Magne

Magne

Hi there!

I got a problem with the control form part. When i drag and drop the widget into a sidebar, i get no "Widget Title" text field. But if i click "save" on the widget, the "Widget Title" text field appears. Any idea why this is happening to me?

Nice article by the way :)

Reply to Magne
Wingam

Wingam

Again great post! Thank you very much! Cristal clear!

Reply to Wingam
Amit

Amit

This is awesome ! Great Article for beginners !!!

Reply to Amit
Alex

Alex

Thanks for the great posts on widget creation. Working on my first one now. Your posts saved me a ton of time.

Reply to Alex
Tom

Tom

Excellent article. Idiot-proof.

Reply to Tom
Luis Milanese

Luis Milanese

I had to create a Wordpress plugin but I had never created one, so guess what? I googled it and I found these two articles and they saved my ass. Thank you VERY much. Would you mind if I translate that to Portuguese so everyone down here in Brazil can make use of it?

Thanks again.

Reply to Luis Milanese
Phillip B

Phillip B

Two excellent tutorials!
Thanks to you I'm already creating and customizing my widgets.

Reply to Phillip B
Kawika

Kawika

Thanks! It's hard to find documentation on how to create WordPress widgets. This post saved my bacon! Would you consider updating it for the newest version of WordPress?

Reply to Kawika
Jabga

Jabga

A great tutorial, thanks a lot sharing this with us

Reply to Jabga
Jason Oakley

Jason Oakley

Hey!
Thanks for this very helpful tutorial. I looked all over the web for information on adding a Control Panel to my widget and this is the most informative and easy to understand tutorial out there.
I've just plugged your tutorial on my site. I hope more will use it to learn.

Thanks again.

Reply to Jason Oakley
Gopinathan

Gopinathan

i need a help for create my own sidebar and how to display in my theme

Reply to Gopinathan
Gopinathan

Gopinathan

I've a problem regarding "How to create my own sidebar and how to post my widget in that" could u help me how to do it,..

Reply to Gopinathan
Dark Avenger

Dark Avenger

This is a great article, with the last one, I have finally got my head around making a widget! Thank you for making it easy!

DA

Reply to Dark Avenger
Mrio

Mrio

That was a very good tutorial! Very well explained. Thanks a lot!

Reply to Mrio
Mike

Mike

2 terrific articles. Well done.

Mike

Reply to Mike
Racing News Digest

Racing News Digest

I know I am really late commenting on this article but I wanted to say this is exactly what I was looking for to implement some special widgest in my WPMU install.

thanks

Reply to Racing News Digest
Steven

Steven

Excellent article, typed "how to make a wordpress widget" into google and 5 minutes later here I am with a working widget

Could you help to add other items into the widget admin?

I would like to have a drop down menu to allow a variable to be selected and used in the widget so if I had optional items to have included in the widget they could select which option they would like.

Reply to Steven
psimbiru

psimbiru

you are the best.....thanks

Reply to psimbiru
Thomas

Thomas

Very useful, thank you!

Reply to Thomas
Donkeyboy

Donkeyboy

Brilliant explanation - cleared up the mysteries of plugins and widgets!

One slight problem: the first time I add the plugin (using the WP interface), it correctly shows the default title - 'My Widget Title'. When I change this title to my own, it also updates fine.

However, when I delete my own title from the widget (still in the WP interface), it doesn't reset itself back to 'My Widget Title'. It just leaves it blank.

I've even removed the entry for that plugin in MySQL. When I come to add the plugin again and a new entry is created in MySQL, that field is not showing the default value - its blank, until I edit it myself.

Am I missing something?

Reply to Donkeyboy
Wes G

Wes G

Excellent tutorial. It was easy to understand and follow, and allowed me to make a widget very quickly.

Thanks!

Reply to Wes G
mrmuscle

mrmuscle

thanks 4 u articles

Reply to mrmuscle
Zack Melayu

Zack Melayu

Your website is one of the best and neat website that I&squot;ve visited. I want to start my own website or blog and would like to have the same basic layout as yours. I appreciate it very much if you could tell me where can i get the template?

Reply to Zack Melayu
Twitter Widget

Twitter Widget

Thank you for these 2 great articles! I was able to quickly create a Wordpress widget for our Twitter widget using your examples.

Reply to Twitter Widget

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.