How can I add links to widget titles?

Making the title click-able

WordPress won’t let you pass HTML code in the title of the widget, but it does have the handy parameters $before_title and $after_title that you can use to manipulate things.

In your widget, just add the first part of the link (<a href="...">) to the end of $before_title and the last part of the link (</a>) to the beginning of $after_title and your title will automatically be linked.

You do this after you extract the arguments in the widget() method … so in your code, find the section:

ob_start();
extract($args);

$title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Staff News') : $instance['title'], $instance, $this->id_base);

And add:

$before_title .= '<a href="http://something.com">';
$after_title="</a>" . $after_title;

Then you’ll be linked!

Changing the default widgets

You can’t apply this method to the default widgets directly, but there is a workaround using object inheritance. Just define your own custom widgets that extend the default widgets:

class My_Widget_Recent_Posts extends WP_Widget_Recent_Posts {

}

You’ll have to redefine the widget name and such in the constructor, then redefine the widget() method by copying what’s already there but applying our $before_title/$after_title hack from above. Your new version of the default widget will have linkable titles!

Leave a Comment