WordPress Widgets provides a simple way to add content and features to sidebars, which can be located in header, footer, and anywhere else in properly designed and structured themes. In addition to WordPress built-in widgets, many plugins add their own widgets for quick deployment on the web pages without coding.

However, not all the themes include widgets support on all areas or positions in the web page layout. The most commonly supported locations are sidebars and footer. Not many know that you can also add widgets to the header, if the theme supports it.

Here’s the simple guide on how to create and add a widget area in the header. The following code should be placed in the active theme’s functions.php file.

Firstly, we need to declare a new widget area (sidebar) with the following code. You can customize and change the code as per your preference, such as using your own name, ID or styling.

<?php
// Add a widget.
if ( function_exists( 'register_sidebar' ) ) {
	register_sidebar( array(
		'name' => 'Header Widget',
		'id' => 'tj-header-widget',
		'description' => 'Widget on Header',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h2>',
		'after_title' => '</h2>'
	) );
}
?>

You can now see the new widget area “Header Widget” or whatever name you chosen in Appearance -> Widget.

Next, we need to display the newly declared sidebar (the above widget area) to a location in the header. There are two ways to go about it.

First method depends on the theme. If your theme has built-in Action or Filter hook which allows you to call your function in the header.php or other PHP file which is called to display the header, then just add a action or filter function to display the sidebar in header.

For example,

<?php
// Add the widget area to the header
add_filter ('hook_in_header', 'tj_add_header_widget');
function tj_add_header_widget() {
	if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Header Widget') ) :
	endif;
}
?>

What if your theme doesn’t provide any hook? In the second method, you need to manually modify the header.php, or whichever template file which displays the header area which you want to insert the widget area. Insert the following code on location which you want the widgets to appear:

// Add the widget area to the header
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Header Widget') ) :
endif;

If you’re modifying the theme’s template file directly, it’s recommended that you edit the child theme to prevent the change from been overwritten when the theme is updated.

Finally, you may need to add in some CSS styles to make the widgets look nice on your pages. But that’s out of scope of this article.