Sidebar / widgets create in wordpress custom theme

Widgets are such an integral part of WordPress themes that it is hard to imagine a WordPress theme without widgets. Widgets are executable scripts that you can simply drag and drop in your sidebars or any other widget ready area in your theme. Many of our readers utilize widgets to add custom elements to their sidebar. However this article is for those curious users who want to learn how to add dynamic widget ready sidebars or widget ready areas in WordPress themes.

functions.php

// sidebar / widget register
register_sidebar([
  'name' => 'Left Sidebar',
  'id' => 'left_sidebar', // this should be unique, because we can call this sidebar using this id
  'description' => 'this is for left sidebar'
]);

OR

function wpdocs_theme_slug_widgets_init() {
   register_sidebar( array(
    'name' => __( 'Main Sidebar', 'textdomain' ),
    'id' => 'left_sidebar',
    'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'textdomain' ),
    'before_widget' => '<li id="%1$s" class="widget %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h2 class="widgettitle">',
    'after_title' => '</h2>',
  ) );
}
add_action( 'widgets_init', 'wpdocs_theme_slug_widgets_init' );
sidebar.php

<?php
  dynamic_sidebar('left_sidebar'); // pass id of sidebar
?>
index.php / page.php

<?php get_sidebar(); ?>

Leave a Reply