[wp-hackers] Sidebar widget HTML/DOM

Michael D Adams mda at blogwaffe.com
Thu Jun 24 19:53:48 UTC 2010

On Thu, Jun 24, 2010 at 12:11 PM, Andrew Nacin <wp at andrewnacin.com> wrote:
> If you want to include extra (and potentially unnecessary) HTML markup
> instead of going the fully jQuery route:
> before_widget - <div class="widget-notitle-content-container">
> before_title - </div><h4>
> after_title - </h4><div class="widget-content-container">
> after_widget - </div>

If you're coding this collapsible widgets stuff for one specific
theme, then that will work since you can decide what the markup will
be.  You could probably also get away without any extra markup by
using some jQuery sibling, child and not selectors.

If you want this to be a plugin that works with any theme (is that the
goal?), you can't change the markup like that.

And since the markup is controlled by the theme, it'd be hard to find
a pure JS solution that works universally (unless you attach something
to the register_sidebar hook to detect the markup the theme is using).

Below is a little plugin that wraps divs around all widgets in all
themes.  It'll probably break styling for some themes, but that's
unavoidable if you want to add markup to widgets.

Maybe add in a CSS rule: .widget-content-container-no-title:empty {
display: none; }

In case this doesn't come through via email: http://pastebin.com/PvJfR9eh

function widget_wrap_register_sidebar( $sidebar ) {
        // Here's what we want: a wrapper div just around the content,
not around the title.
        $sidebar['after_title'] .= '<div class="widget-content-container">';
        $sidebar['after_widget'] = "</div>{$sidebar['after_widget']}";

        // But if a widget is titleless, the above will result in an
unpaired </div>
        // So we do the next two lines to ensure we always have valid HTML
        $sidebar['before_widget'] .= '<div
        $sidebar['before_title'] = "</div>{$sidebar['before_title']}";

        remove_action( 'register_sidebar', 'widget_wrap_register_sidebar' );
        register_sidebar( $sidebar );
        add_action( 'register_sidebar', 'widget_wrap_register_sidebar' );

add_action( 'register_sidebar', 'widget_wrap_register_sidebar' );

More information about the wp-hackers mailing list