Programmatically create widget area Wordpress theme

In wordpress, widget is very useful part for our website and we can get it from wordpress dashboard.

Appearance ===> Widget

Widget area wordpress admin

Widget area is a part of wordpress theme structure where widgets can be added. Widgets area may be in right side of main content or left side of it.

It can be created in header part of a website.Widgets can also be created in footer area or in the middle posts of website.

It can be created almost everywhere where you want. Widget areas also referred as “Sidebars”.

To add a wigdet, go to wordpress admin bar

Go to Appearance  === > Widgets

Drag a widget to a widget Area.

Add widget in widget region

Most new themes are widgetized, now you can check your theme widgets section for that.

Show calender widget area in footer

“Plugins” also create widgets to display contents or some other special features.

Creating A Widget Area

It is a two step process.

1. Registering a Widget Area

Add the following code in your theme’s “functions.php” file.

/** * Register Widget Area. * */ function widgets_sidebar_init() { register_sidebar( array( 'name' => 'Header Sidebar', 'id' => 'header_sidebar', 'before_widget' => '<div>', 'after_widget' => '</div>', 'before_title' => '<h2 class="rounded">', 'after_title' => '</h2>', ) );} add_action( 'widgets_init', 'widgets_sidebar_init' ); 

2. Display Widget Area

To display widget area add the following code to location of your choice in your theme file.

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('header_sidebar') ) : endif; ?>

where “header_sidebar” is the id of widget area.

To view new created widget area you can go to ” Appearance  ==> Widget“. There must be a widget area of name ” Header sidebar “.

Create new widget area in theme