Saturday 16 July 2016

Register and Display a Sidebar in Wordpress

To register and display the Sidebar in WordPress you have to follow the two steps.

Step: 1 You have to add this in the Function.php file in your theme
Below the "wpb alone should be replaced by your theme name"

function wpb_widgets_init() {
    register_sidebar( array(
        'name' => __( 'Main Sidebar', 'wpb' ),
        'id' => 'sidebar-1',
        'description' => __( 'The main sidebar appears on the right on each page except the front page template', 'wpb' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => '</aside>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ) );
    register_sidebar( array(
        'name' =>__( 'Front page sidebar', 'wpb'),
        'id' => 'sidebar-2',
        'description' => __( 'Appears on the static front page template', 'wpb' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => '</aside>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ) );
    }
add_action( 'widgets_init', 'wpb_widgets_init' );

Step: 2 Display it Dynamically in the Page where ever you want by adding the below code

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
    <div id="secondary" class="widget-area" role="complementary">
    <?php dynamic_sidebar( 'sidebar-1' ); ?>
    </div>
<?php endif; ?>

Note: " is_active_sidebar( 'sidebar-1' )" - The sidebar-1 is the id of the registered sidebar in the function.php file. If the id is not used properly the Sidebar will not be displayed even if the registration is correct.

No comments:

Post a Comment

Email Code PHP

This is a Simple Code which is written in the PHP for Sending Emails from One Server to all the Other Domains. It is very easy and little C...