Sunday, 25 November 2018

How to Insert Custom Widget in Header Section of Wordpress Theme

Step 1. Creating a Header Widget Area

ou will need to add this code to your theme’s functions.php file.
1
2
3
4
5
6
7
8
9
10
11
12
13
function wpb_widgets_init() {
 
    register_sidebar( array(
        'name'          => 'Custom Header Widget Area',
        'id'            => 'custom-header-widget',
        'before_widget' => '<div class="chw-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="chw-title">',
        'after_title'   => '</h2>',
    ) );
 
}
add_action( 'widgets_init', 'wpb_widgets_init' );

Step 2: Display Your Custom Header Widget

You will need to edit the header.php file in your theme and add this code where you want to display your custom widget area.
1
2
3
4
5
6
7
8
<?php
 
if ( is_active_sidebar( 'custom-header-widget' ) ) : ?>
    <div id="header-widget-area" class="chw-widget-area widget-area" role="complementary">
    <?php dynamic_sidebar( 'custom-header-widget' ); ?>
    </div>
     
<?php endif; ?>

Step 3: Style Your Header Widget Area Using CSS

Here is some sample CSS to help you get started.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
div#header-widget-area {
    width: 100%;
    background-color: #f7f7f7;
border-bottom:1px solid #eeeeee;
    text-align: center;
}  
h2.chw-title {
    margin-top: 0px;
    text-align: left;
    text-transform: uppercase;
    font-size: small;
    background-color: #feffce;
    width: 130px;
    padding: 5px;
    }