Wordpress - Adding a div to wrap widget content after the widget title

In addition to Toscho's answer here's what you need for a robust solution:

// if no title then add widget content wrapper to before widget
add_filter( 'dynamic_sidebar_params', 'check_sidebar_params' );
function check_sidebar_params( $params ) {
    global $wp_registered_widgets;

    $settings_getter = $wp_registered_widgets[ $params[0]['widget_id'] ]['callback'][0];
    $settings = $settings_getter->get_settings();
    $settings = $settings[ $params[1]['number'] ];

    if ( $params[0][ 'after_widget' ] == '</div></div>' && isset( $settings[ 'title' ] ) && empty( $settings[ 'title' ] ) )
        $params[0][ 'before_widget' ] .= '<div class="content">';

    return $params;
}

From Toscho's answer:

register_sidebar(array(
    'name' => "Sidebar1",
    'id' => 'home-sidebar-1',
    'before_widget' => '<div class="sidebar-box">',
    'after_widget' => '</div></div>',
    'before_title' => '<div class="title">',
    'after_title' => '</div><div class="content">',
));

What this does is:

  • checks the settings for the registered sidebar for widgets ending in 2 closing <div>s
  • checks if there's no title
  • if not, it modifies the before_widget output to show the opening widget content div

You could use this approach to change the sidebar arguments in other ways to based on the widget instance's settings.


Add the second div to the title parameter:

register_sidebar(array(
        'name' => "Sidebar1",
        'id' => 'home-sidebar-1',
        'before_widget' => '<div class="sidebar-box">',
        'after_widget' => '</div></div>',
        'before_title' => '<div class="title">',
        'after_title' => '</div><div class="content">',
    ));

I liked the idea of both @tosco and @sanchothefat answers - however I have struggled with that combination because whilst empty( $settings[ 'title' ] might indeed return true the widget itself might output a default title if none is set. This title is then wrapped in the before_title and after_title markup and again the page breaks. That's the case with some of the default widgets anyway.

Easier to just stick to standard widget registration parameters;

register_sidebar(array(
    'id' => 'sidebar1',
    'name' => __( 'Sidebar 1', 'bonestheme' ),
    'description' => __( 'The first (primary) sidebar.', 'bonestheme' ),
    'before_widget' => '<div class="block">',
    'after_widget' => '</div>',
    'before_title' => '<div class="block-title">',
    'after_title' => '</div>',
));

and then add a filter action as per Marventus' answer here;

http://wordpress.org/support/topic/add-html-wrapper-around-widget-content

function widget_content_wrap($content) {
    $content = '<div class="block-content">'.$content.'</div>';
    return $content;
}
add_filter('widget_text', 'widget_content_wrap');