How to add a widget area anywhere on a WordPress site

Adding a widget area to your theme

Adding widget areas can be quite useful on a site. Maybe you want to place a banner ad in you header or above your header or anywhere else. I’m going to try to make this as easy as possible.

Just keep in mind that whenever you update your theme, you might loose the settings.

How to register the widget area

Add the following code to you functions.php file in your theme folder.
(..wp-content/themes/yourtheme/functions.php)
I usually add it at the end of the file right before the last ?>

if ( function_exists('register_sidebar') ){
register_sidebar(array(
'name' => 'header_widget_area',
'before_widget' => '<div id="header_widget_area">',
'after_widget' => '</div>',
'before_title' => '',
'after_title' => '',
));
}

Change the ‘name’ to something that suits you. I in this example I have chosen “header_widget_area”. Make sure there are no spaces in the name. The “div id” is the name you will use if you want to add your own css styles later. I usually use the same name.

Choose where to place the widget

Now that you’ve registered the widget area, you need to choose where to put it.
I will assume you have some basic knowledge of the layout of the page so I won’t go to deep into that. Let’s assume you want to add this widget area in you header just like me, then you would add the following code to your header.php file in you themes folder.

<?php
// Widgetized area
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('header_widget_area') ) : ?><?php endif;
// End of widgetized area
?>

You need to place it somewhere between two divs ( ?> enter code here <div id..)
After you’ve saved these changes you should check the dashboard to see if you’ve succeed creating the widget area. In this example you would have a new widget area called header_widget_area. Try adding something to it to see if it shows up on your site.

If the widget shows up but in the wrong place, just move the above code around in the header.php (always in between two divs) -file until you get it “almost” where you want it. After it’s placed pretty good, you can create your own css to add any special settings, like padding, margin, backgrounds and stuff. To add a black background and move the widget 20px to the left you would add this code

#header_widget_area {
background: black;
margin-right: 20px;
}

And to change the text color to white, you would type

#header_widget_area a {
color: white;
}

To add custom css to your theme you might want to create a child theme or download a plugin (just search for “custom css” and you’ll probably find what you want) You can also add it directly to your style.css in your themes folder, although you will loose the settings as well as all the above every time you update your theme. So keep that in mind so you can backup your settings.

Hope it helps!