How to Create a New Widget Area in WordPress

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we have cloned the TwentyThirteen template and called it TwentyCustom so that we can make modifications to TwentyCustom without the fear of our customization being overwritten when we do a WordPress update.

We show how to add a new widget area in the header of TwentyCustom.  Here is the final results where we have added the search widget to our new widget area in the header…

new widget area in wordpress

new widget area in wordpress

 

1.  The original header code in header.php looks like this …

original header code

original header code

 

2. We alter the template code in header.php to make room for the new widget area …

new header code

new header code

3. Note that we have partitioned the header 60% to 40% floated left.  We bound that in a containing div that uses the micro-clearfix technique to clear floated divs.  We confirmed that this class “clear” is already defined in the style.css file of the template.

The latter partition contains the dynamic sidebar called “header-1”.  Dynamic sidebar is wordpress way of saying “widget”.  We are naming our new widget area “header-1”.  We show this header area with “dynamic_sidebar” only if the widget area “header-1” is_active_sidebar.

4. Right now, if you preview the site, you see no change.  To make widget “header-1” active, add the following code to functions.php in the TwentyCustom  theme …

code to register widget

code to register widget

This is known as registering the widget area.  The code may seem mysterious and difficult to remember.  But we found an example of this code to follow by searching “register_sidebar” in functions.php and you see similar code.  This was how the theme TwentyThirteen registered its existing Main and Secondary widget area.

The “add_action” line uses WordPress’s widgets_init hook.   When wordpress start initializing widgets, that event triggers and call our arbitrarily named function “header1_widgets_init”.  By convention, we usually have the suffix of the function match the hook.

Our function header1_widgets_init is defined in the above code.  It calls the WordPress function register_sidebar which takes array of key-value pairs, where you fill in the values.

5. Once registered, you can drop widgets into the new widget area via your dashboard …

add widget to new widget area

add widget to new widget area

The text you see “Header Widget Area One” and “widget in the header area” comes from the values you passed into the above function.

6.  View your widget in new widget area …

new widget area in wordpress