Christian Schlensker
Christian Schlensker

Reputation: 22478

Remove empty titles in wordpress sidebar widgets

I have registered a wordpress sidebar like so:

register_sidebar( array(
    'name' => __( 'First Sidebar', 'theme_name' ),
    'id' => 'primary-widget-area',
    'description' => __( 'The primary widget area', 'theme_name' ),
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
) );

The problem is that when the title is empty, the h3's still get rendered. Is there a way to remove these when the title is left blank?

Upvotes: 2

Views: 5543

Answers (5)

Mhaddy
Mhaddy

Reputation: 43

Wanted to thank Daniel James for his snippet - this is beautiful. I made a small change where I replaced   with !no_display, then added !no_display to the title of my widgets in the front-end. This made it clear to my users that it was a hook to be referenced in a function (and not to be confused with a seemingly empty widget title).

Upvotes: 1

Daniel James
Daniel James

Reputation: 3939

This is just a small addition to Mark's answer. The default calendar widget uses &nbsp; if the title is empty, so it still displays an empty header. I worked round that by adding this to my theme's functions.php:

function foo_widget_title($title)
{
    return $title == '&nbsp;' ? '' : $title;
}
add_filter('widget_title', foo_widget_title);

Changing 'foo' to something appropriate.

Upvotes: 4

two7s_clash
two7s_clash

Reputation: 5827

Register two sidebars, identical but for the 'before_title' and 'after_title' values. Check for a title, and then call one or the other accordingly.

Upvotes: 0

Mark
Mark

Reputation: 3271

Printing the before_title and after_title is something that is done in the function widget( $args, $instance ) by the widget self. All of the default wordpress 3.1 widgets check if the title is empty before parsing before_title and after_title, but I guess you're using a custom widget from a theme or plugin, in that case you'll have to adjust the widget( $args, $instance ) code.

Upvotes: 1

Christopher
Christopher

Reputation: 1102

Edit the template and check for the existence of a title. If no title is set do not print the h3.

Upvotes: 0

Related Questions