Creating a Widget Area in WordPress

One of the beauty of having a custom theme for your website is you get the chance to decide where to place certain elements of your site. In WordPress, if you write your theme from scratch, you will be able to decide in which parts of your site you want to display your widgets. This tutorial will teach you how to create a widget area in the sidebar of a website built with WordPress.

1. Add the following lines of code to the functions.php file:

// Adding widget areas
function add_widget_support() {
     register_sidebar( array(
           'name'          => 'Sidebar',
           'id'            => 'sidebar',
           'before_widget' => '<div>',
           'after_widget'  => '</div>',
           'before_title'  => '<h2>',
           'after_title'   => '</h2>',
       ) );
add_action( 'widgets_init', 'add_widget_support' );

The code above is for one widget area. If you want to create another widget area, just add another register_sidebar array after the two closing parentheses and semi-colon for the first register_sidebar. Do not change the word sidebar in register_sidebar. It is a fixed expression in WordPress. Even if you plan to add the widget area to the footer of your website, still use register_sidebar and nothing else. You are only allowed to change the values to the right of name, id, before_widget, after_widget, before_title, and after_title.

2. Add the following bits of code to the sidebar.php file:

<?php if ( is_active_sidebar( 'sidebar' ) ) : ?>
	<aside id="primary-sidebar" class="sidebar sidebar-right widget-area" role="complementary">
		<?php dynamic_sidebar( 'sidebar' ); ?>
<?php endif; ?>

The word sidebar in ( ‘sidebar’ ) in the above code refers to the value to the right of id in Step 1.

If you followed the two steps above, you can now go to Appearance > Widgets in the dashboard of your WordPress site and start dragging your widgets into your created widget area.