Would you like to add new sidebar to your WP website but you afraid about hard to understand the code. Don’t worry.  I will show you two small pieces of code that make it works. Let’s go.

At first, you should add this code to functions.php file inside the root of your theme directory.

if ( ! function_exists( 'wpi_widgets_init' ) ) {
    /**
     * Add dynamic sidebars in WordPress
     */
    function wpi_widgets_init() {
        register_sidebar(
            array(
                'name'          => esc_html__( 'Header', 'wpi-lang' ), // name visible in WP dashboard
                'id'            => 'header', // just ID of sidebar
                'before_widget' => '<div id="%1$s" class="wpi-widget widget %2$s"><div class="wpi-widget-in clearfix">', // HTML before each widget
                'after_widget'  => '</div></div>', // HTML after each widget
                'before_title'  => '<h3 class="wpi-title">', // HTML before widget's title
                'after_title'   => '</h3>' // HTML after widget's title
            )
        );
    }
    add_action( 'widgets_init', 'wpi_widgets_init' ); // add new sidebar to WP widgets
}

There are comments to explain what particular lines are doing.  Now we see our image in Appearance -> Widgets.

add new sidebar

Now you need to decide where this sidebar will be displayed. In our example, we want to show it in a single post view. To do that we need to add above code in file single.php in the root of your theme directory.

if ( is_active_sidebar( 'header' ) ) : ?>
    <div id="wpi-header">
        <?php dynamic_sidebar( 'header' ); ?>
    </div>
<?php endif;

Now our sidebar will be displayed in a single post ( detailed place depends on what theme we are using ).

Share this post

Leave a Reply

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