How to create sidebar areas and widgets in a WordPress theme

The word widget is a programming term that means a user interface element (GUI), and it is used in many platforms, including the WordPress system. It allows WordPress site owners to add custom content or different functions and features and display them within specific places such as sidebars or in the header or footer of your WordPress site. Without the need to write any programming code.

In this article from the WordPress template development course, we will show you how to define widget areas yourself, how to add elements to them and display them in different places on the site. We will also explain in detailed steps how our widgets can be programmed in a WordPress template, and how to display and deal with them manually through code. Programmatic.

What are widgets and how do I display them on a WordPress site?

As I mentioned at the beginning, widgets are nothing but blocks or blocks that display a customized piece of content and allow users to customize their website without having to write code.

Core WordPress includes many ready-made widgets built into it, known as (Built-in Widgets), such as the calendar, the latest articles, a list of tags, the search bar, RSS feeds, categories, archives, the latest comments, and many more.

Many WordPress themes and WordPress plugins add their own widgets to your WordPress website. You can find all the user interface elements or widgets available on your site by logging in to your site’s control panel > and choosing Appearance > Widgets.

Here you will see the widget management page shown in the following image, which shows you all the widget areas or sidebars available in your template. Within these positions, you can place any widget by clicking on the + button, which shows you all the widgets of your site.

Widget display areas in a WordPress template

WordPress itself includes a standard set of widgets that you can use with any theme. You can also create custom widgets or user interface elements other than the default ones and display them in your WordPress theme through code, as we will explain in the subsequent paragraphs of this article.

note:

The Widgets page is not the only way to add widgets to your WordPress site, as you can also add and customize widgets through the theme customization page by going to Control Panel > Appearance > Customize > Widgets tab , or by clicking on the Manage with Live Preview link shown on To the left of the previous image, but be careful, as in this case you will not see all the widgets and sidebar areas.

Steps to add sidebars and widgets programmatically to a WordPress theme

If you want to include your template with one or more sidebars in order to allow the site owner to add whatever widgets or user interface elements they want to these bars, and control them through the control panel of his WordPress site, follow these steps:

Step1. Define custom widget areas with the register_sidebar function

You first need to define the widget areas where you want widgets to be included within your WordPress theme. Within these areas, you will add whatever widgets you want, and then you will later display them wherever you want according to the design of your template.

To do this, we use the register_sidebar function in the template functions file functions.php, which is a ready-made function in WordPress that defines the sidebar areas. All you have to do is pass an array or series of parameters as follows:

register_sidebar( array|string $args = array() )

We pass to the function the following matrix of parameters:

  • ‘name’ : A string representing the name of the sidebar displayed on the widget management page.
  • ‘id’ : Unique identifier for the sidebar.
  • ‘description’ : Description of the sidebar that will appear when the widget is selected on the Widgets page
  • ‘class’ : A string representing an additional CSS class that is useful for styling a sidebar.
  • ‘before_widget’ A string representing the HTML content (opening tag) that is assigned before each widget output when assigned to a sidebar or a specific area.
  • ‘after_widget’ A string representing the HTML content (closing tag) assigned after each widget output when assigned to a specific widget area. ‘before_title’ A text string representing the HTML content (opening tag) that is assigned before the sidebar title when it is displayed on the site.
    ‘after_title’ A text string representing the HTML content (closing tag) that is assigned after the sidebar name when it is displayed on the site.
  • ‘before_sidebar’ A string representing HTML content that precedes the entire sidebar when it is displayed.
  • ‘after_sidebar’ : A string representing the HTML content that is based on the entire sidebar dimension when it is displayed.
    ‘show_in_rest’ : This parameter is a boolean value that specifies whether we want to make the sidebar public for the REST API. The default value is to display the sidebar only to users with the admin role

This function is usually called via the widgets_init action hook , which registers all default widgets on startup.

Read more: Explanation of WordPress Hooks and their importance for theme and plugin developers

Note :
You can register a sidebar through the function register_sidebar () for each bar separately, or register several sidebars at the same time using the function register_sidebar s () , which takes the same parameters as the previous function in addition to an additional parameter that specifies the number of areas or sidebars that you want to add.

A practical application for registering two areas and widgets in a WordPress template

If you want your theme to include two logics for including widgets, for example:

  • Sidebar area
  • Area Footer1

You need to edit the functions.php file and add the following code to it:

* ==========================================================================
* Register two widgets area
* ========================================================================== */
if ( ! function_exists( ‘olatheme_widgets_init’ ) ) :
function olatheme_widgets_init() {
register_sidebar( array(
‘name’ => ‘Sidebar’,
‘id’ => ‘sidebar’,
‘description’ = > ‘This area appears in the sidebar of the site’ ,
‘before_widget’ => ‘<li id=”%1$s” class=”widget %2$s”>’,
‘after_widget’ => ‘</li>’,
‘before_title’ => ‘<p class=”wtitle”>’,
‘after_title’ => ‘</p>’,
) );
register_sidebar(
array(
‘name’ => ‘Footer1’,
‘id’ => ‘footer-1’,
‘description’ = > ‘This area appears in the first column in the footer of the site’ ,
‘before_widget’ => ,
‘after_widget’ => ,
‘before_title’ => ,
‘after_title’ => ,
)
);
}
endif;
add_action( ‘widgets_init’, ‘olatheme_widgets_init’ );

Now you can go to Control Panel > Appearance > Widgets and you will see that the two areas have already been added to your template as shown in the following image:

Define custom areas for displaying widgets

As you can see in the image above, you can simply click the + button under each area and add any ready-made widgets you want to it, or you can define your own widget through code, as I will explain in step 3.

Step2. Display widget areas through the dynamic_sidebar function

The next step is to display these areas in the places we choose in your template. For example, to display the content of the area on the home page of the site, you must edit the file index.php and display in it the area you want by calling the dynamic_sidebar function and passing an argument that represents the identifier or name of the sidebar or the area you want for it. To display this area on the single post page, you must edit The file single.php displays the area you want in it, and so on..

However, as you can see, this method may cause the same code to be duplicated in several places in the template, so you can alternatively define the widget display code in a custom sidebar.php file that includes the code for displaying the widget areas as follows:

<!– BEGIN #sidebar –>
<aside id=“sidebar”>
<ul>
<?php if ( is_active_sidebar( ‘sidebar’ ) ) :
dynamic_sidebar( ‘sidebar’ );
endif; ?>
</ul>
</aside>
<!– END #sidebar –>

In this way, you can call the contents of the file when needed in any of the template’s template files through the ready-made function in WordPress get_sidebar , which loads the template’s sidebar template.

For example, when called in the index.php file and before the code intended to display the footer, the sidebar will appear to us on the main page of the site as follows:

Display sidebar widgets on the home page of the site

3. Defining custom widgets in a WordPress template through code

As we explained in the previous paragraphs, you have several options for adding a widget to the widget areas in a WordPress template, either through the default widgets provided by WordPress, or through the widgets known by other plugins and templates. How can you write code to define a custom widget within your template? This is what I will explain to you in this paragraph

It is possible to write a custom widget identification code in more than one place within a WordPress site, either through the template functions file functions.php, in which case this widget will only be visible when your template is activated on the site, or by developing a custom plugin and pasting the custom widget creation code into it. In this case, the widget can be kept available on the site, regardless of the template used. Read more: How to develop WordPress plugins yourself to automate functions

In this article, we will adopt the first method for ease and write the custom widget code in the template functions file. We will create a simple widget whose task is to display the name of the site and below it a welcome message for site visitors, as shown in the following figure:

We will make the site name in the widget dynamic, so that the site owner can specify the name of his site by entering it into a text field in a form that we create specifically for this widget.

To define this custom widget, you can rely on a ready-made class in WordPress called WP_Widget . This programming class is directed to developers and includes a definition of 19 methods that can be used to develop custom widgets. The most important of these methods that the class defines are:

  • __construct  : A builder method through which we create the widget by specifying the ID, title, and description.
  • form : This method enables us to create a form or form through which we can enter the widget options through the backend.
  • widget : Through this method, we determine the output of the widget.
  • update : Through this method we can save the widget options in the database

We will name our widget (WordPress Widget in Arabic) and give it the unique identifier wpar_widget and follow the following steps to create it:

  • We define the purpose of the WP_Widget class in functions.php as follows:
// Create a widget intent
class wpar_widget extends WP_Widget {
function __construct() {
parent::__construct(
‘wpar_widget’ ,
‘WordPress widget ‘ ,
array ( ‘description’ = > ‘Simple widget to welcome website visitor’ , ‘wpar_widget_domain’ )
);
}
  • Then we write the backend code for the site, and we define the widget customization form that contains a text field as follows:
// Create a backend form for the widget
public function form( $instance ) {
if ( isset( $instance[ ‘sitetitle’ ] ) ) {
$websitetitle = $instance[ ‘sitetitle’ ];
}
else {
$websitetitle = ‘Website title here’ ;
} ?>
<p>
<label for=“<?php echo $this->get_field_id( ‘sitetitle’ ); ?>”><?php _e( ‘wppr’ ); ?></label>
<input class=“widefat” id=“<?php echo $this->get_field_id( ‘sitetitle’ ); ?>”
name=“<?php echo $this->get_field_name( ‘sitetitle’ ); ?>” type=“text” value=“<?php echo esc_attr( $websitetitle ); ?>” />
</p>
<?php
}
  • The next step is to write the front-end code for the widget
// Create the front end of the widget
public function widget( $args, $instance ) {
$websitetitle = apply_filters( ‘widget_title’, $instance[‘sitetitle’] );
// before and after widget arguments are defined by themes
echo $args[‘before_widget’];
if ( ! empty( $websitetitle ) )
echo $args[‘before_title’] . $websitetitle . $args[‘after_title’];
echo ‘Welcome to our website’ ;
echo $args[‘after_widget’];
}
  • Finally, we determine how to process the changes made to the widget, and we save the widget and load it into WordPress.
// Update the old widget with the new widget
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance[‘sitetitle’] = ( ! empty( $new_instance[‘sitetitle’] ) ) ? strip_tags( $new_instance[‘sitetitle’] ) : ;
return $instance;
}
}
// Register the new widget
function wpar_load_widget() {
register_widget( ‘wpar_widget’ );
}
add_action( ‘widgets_init’, ‘wpar_load_widget’ );

After adding the previous code, go back to the control panel and choose Appearance > Widgets > and click on the + button to view the available widgets. You will see the new widget that you just created called (WordPress Widget in Arabic) present with the list of widgets available in WordPress. All you have to do is click on it. To add it to one of the widget display areas. Here I added it on top of the sidebar area.

Then customize it and enter your website name in the widget form as follows:

That’s it! Click the Refresh button and view your site’s home page and you will see the Welcome Message widget displayed in the sidebar of your page

For more information about defining custom widgets, I recommend reading the following article on the official WordPress theme developer website.

Conclusion

In today’s article, we learned about widgets, which are considered one of the important parts of the WordPress template, which are simply blocks that perform a function or display a specific feature that you can add in the sidebars of your site, or in another area ready for user interface elements in your WordPress template.

In today’s article, we explained in detail how to add and register custom areas for displaying the website in WordPress templates in order to allow the site owner to add the elements he wants in them. Then we explained how to display these areas on the front end of the site by calling them in the template template files or anywhere else we want to display them. In it, we finally learned how to define our own widget and include it in our template through code.

If you are a WordPress theme developer, you can take advantage of the widgets feature to enhance your theme, and enable users of this theme to easily add distinctive dynamic elements to their sites through a simple drag-and-drop interface.

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.