WordPress.org

Ready to get started?Download WordPress

Forums

Add HTML wrapper around widget content (1 post)

  1. cmoral3s
    Member
    Posted 1 year ago #

    I have the same problem described in this topic that, despite not being resolved for me, was closed:
    http://wordpress.org/support/topic/add-html-wrapper-around-widget-content

    I want to add a div to the widget content, like this:

    <aside class="widget">
         <h1>widget title</h1>
        <div class="widget-content">
            some content
         </div>
    </aside>

    The only way I found to do so was putting this when registering the sidebar:

    register_sidebar(array(
            'name' => __('', ''),
            'description' => __('', ''),
            'id' => 'about-bottom',
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</div></aside>', //Close "widget-content" div
            'before_title' => '<h1 class="widget-title">',
            'after_title' => '</h1><div class="widget-content">'
        ));

    The problem with this solution is that, if some widget is added without a title, it breaks the code (a div that was never created is closed).
    In the other post that I've linked, it was suggested to use the widget_text filter, but that only works for the Text Widget, not for any other type of widget.

    I found a way to check for the absence of a title with a function:

    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></aside>' && isset($settings['title']) && empty($settings['title'])) {
            $params[0]['before_widget'] .= '<div class="widget-content">';
        }
        return $params;
    }

    The problem is that this function fails to deal with default titles. Some widgets (like many of the built-in WP ones) set a title if nothing is set on the admin, like this:
    $title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts') : $instance['title'], $instance, $this->id_base);

    So the previous function "thinks" there isn't a title set and adds the extra div, but a title is set after that check is done and so the code is messed up again.

    Is there any way to check for the real title of the widget, or any other hook to use?

    Thanks

Topic Closed

This topic has been closed to new replies.

About this Topic