WordPress Tips

Add link to title of widget text, or any widgets

December 28, 2016

Sometimes you want to add link to the Widget Title. Using “widget_title” filter you want do that. Below is a simple way to do that. Let’s start with the code

add_filter('widget_title', 'my_widget_title_filter', 10, 3);
function my_widget_title_filter( $title, $instance, $id_base){
if($id_base == 'text'){
// so we only want to apply on Text Widget
if($title == 'Widget Text'){
$title = '<a href="#">' . $title . '</a>';
}
}

return $title;
}

So the “widget_title” filter accepts 3 parameters. The first one is the current title, the second one contains all parameters of the widget. The last one helps us to recognize what type of widget it is. So, we check

$id_base == 'text'

to make sure you only want to apply on Text Widget. Actually this check is not necessary if you don’t care about this. Next, we check which title should be added link. This will be tricky if you have different widgets having same title. Make sure widgets have different titles, so the link only be added to one widget.

Finally, we add link to the title. This solution is not perfect, but simple and fast enough to be used.

You Might Also Like