How to add default Widgets to a custom dynamic sidebar

I have added my custom dynamic sidebar using this code in WordPress

register_sidebar
(array(
'name' => __( 'My widget' ),
'id' => 'right-sidebar',
'description' => __( 'Widgets in this area will be shown on the right-hand side.' ),
'before_title' => '<h1>',
'after_title' => '</h1>'
));

Now I can see this dynamic sidebar in the WordPress admin, via Dashboard -> Appearance -> Widgets.

Read More

When I activate the Theme, by default this dynamic sidebar displays no content; to display Widgets (e.g. Recent Posts, Pages, Category) I have to drag them into the My Widget dynamic sidebar.

But I want the My Widget dynamic sidebar to display three Widgets (Recent Posts, Pages, Category) by default, similar to the dynamic sidebars in Twenty Ten or Twenty Eleven.

Related posts

Leave a Reply

3 comments

  1. This is fairly easy to do, using dynamic_sidebar() and the_widget().

    This is the construct for displaying default content, if no Widgets are added to a dynamic sidebar:

    <?php
    if ( ! dynamic_sidebar( 'My_Widget' ) ) {
        // default content goes here
    }
    ?>
    

    So, to output specific Widgets as default content, simply call the_widget($widget, $instance, $args). For example, to display the “Recent Posts” Widget:

    <?php
    if ( ! dynamic_sidebar( 'My_Widget' ) ) {
        the_widget( 'WP_Widget_Recent_Posts' );
    }
    ?>
    

    (See the linked Codex references for additional usage examples, and $instance/$args values, for each Widget.)

  2. Well, it is a normal behavior, you just have to set default content for this sidebar in your theme. Take a look at twentyeleven/sidebar.php, you can do the same thing :

    <?php if ( ! dynamic_sidebar( 'right-sidebar' ) ) : ?>
      Default content
    <?php endif; ?>
    

    And don’t mistake, a sidebar is not a widget, it is a widget area.

  3. Its possible but not in terms of auto activate.
    What you need to do in the place where you required widget (suppose sidebar) sidebar is truly widget-ready and the administrator pops a new sidebar widget into the lineup, things will automatically switch over to use the admin’s specified settings.

    So yes, you can do it as a default.Not as auto active…

    For more information https://stackoverflow.com/a/3057665/716492