Last Updated: February 25, 2016
·
3.102K
· leonardodna

Widget title on before_widget tag class

User @dalenberg asked on my previous widget tip if we can add the title on the widget as a whole. Actually we can, but it's a little tricky than the previous tip. Here is the whole code:

add_filter( 'widget_display_callback', 'add_widget_title_to_before_widget', 10, 3 );
function add_widget_title_to_before_widget( $instance, $widget_class, $args ) {
    if ( ! empty( $instance['title'] ) ) {
        $new_class = 'class="' . sanitize_title( $instance['title'] ) . ' ';
        $args['before_widget'] = str_replace('class="', $new_class, $args['before_widget']);
        $widget_class->widget( $args, $instance );
        return false;
    }
}

Let's explain: widget_display_callback is the last filter to be used before calling the widget() function. But as we can't alter the $args array, we need to run the widget() method inside our function.

$new_class = 'class="' . sanitize_title( $instance['title'] ) . ' ';
$args['before_widget'] = str_replace('class="', $new_class, $args['before_widget']);

First, we check if we have a title. If true, we perform a str_replace() to add the title on the before_title parameter generated by the register_sidebar() function.

$widget_class->widget( $args, $instance );
return false;

Now, we call the widget() function using our altered $args. Returning false will prevent WordPress to run the widget() function again, so we don't get duplicated widgets.

3 Responses
Add your response

Lame... just kidding, that's why you are my WP guru <3

over 1 year ago ·

Nice, but when you have a widget without a title it doesn't display. You can fix that by adding an else statement:

else:
$widget_class->widget( $args, $instance );
return false;

over 1 year ago ·

Thanks for pointing this out, @mikeymo! :)

We can also move the widget call outside the IF, to make cleaner

function add_widget_title_to_before_widget( $instance, $widget_class, $args ) {
    if ( ! empty( $instance['title'] ) ) {
        $new_class = 'class="' . sanitize_title( $instance['title'] ) . ' ';
        $args['before_widget'] = str_replace('class="', $new_class, $args['before_widget']);
    }
    $widget_class->widget( $args, $instance );
    return false;
}
over 1 year ago ·