Add a custom widget area for custom WordPress theme – Theme development

By Faruque Ahamed Mollick

This tutorial is related to WordPress theme development. Reading this tutorial may be helpful for WordPress theme developers.

We always notice that after installing and activating a WordPress theme the theme provides some widget area. In this widget area, we can add contents that available for the widget. From the admin panel, we just have to drag and drop widget items.

But, we may design and develop our own WordPress theme for our site or for clients or just to sell it online. In these cases, we have to add the widget area to our theme. So we have to learn how to add our own widget area to our WP theme.

Adding widget area in our theme is easy. Using widgets_init action hook we can add a custom widget area in our theme.

Steps to create a custom widget area in for WordPress theme

We are going to follow the steps for adding a custom widget:

1. Open your theme’s functions.php file.

2. Put the below code in that file:

add_action( 'widgets_init', 'cs_widget_init' );
function cs_widget_init() 
{
    register_sidebar( 
        array(
        'name' => __( 'Main Sidebar', 'theme-slug' ),
        'id' => 'main-sidebar',
        'description' => __( 'This widget will be shown on the sidebar.', 'theme-slug' ),
        'before_widget' => '<div class="widget">',
  'after_widget'  => '</div>',
  'before_title'  => '<p class="wid-title">',
  'after_title'   => '</p>',
    ) );
  
}

The above PHP code will add the widget with the name “Main Sidebar”. Now if we go to our Appearance > Widgets, then we will be able to see our widget area. In our code, we have set id for our widget which should be unique for a theme. Also, we have added the id, class so that we can apply the style to our widget and its contents.

3. Now in this post, we are going to show the content of our widget on the front end. Below is the code which we have to add to our theme template file:

<?php dynamic_sidebar( 'main-sidebar' ); ?>

That’s it. Now any item we add to our custom widget area will appear on the front end.

Is that not so cool? We have just created our own custom widget area for our custom theme. Creating widget area is an important part of WordPress theme development.

The first image of WordPress post as featured if not set

WordPress code – show/hide for logged in users in theme

If you are a theme developer then this tutorial may be helpful for you. For further information contact us or write in the comment box below.

Leave a Reply

Your email address will not be published. Required fields are marked *