Modifying Widget Titles in WordPress

On a recent project, my client wanted graphical headers for the widgets on her WordPress blog. Unfortunately, widgets are not that easily themed. Nor can you do this in CSS.

The internet was no help. Lots of people were suggesting using a “dyamic_widget_params” filter. Nope, that isn’t what I want. I don’t want to modify before and after the title, I want to actually change the title.

But, with some poking around, I figured it out. It’s actually pretty easy.

The trick is to use the ‘widget_title’ filter, and the ‘link_category’ filter. Both of these pass the title itself to your function.

Here’s my code, fix the path for your theme and put in the theme’s functions.php file:


/**
 * Show a graphic title if one matches
 */
function fancy_title($title) {
 $clean = strtolower(str_replace(' ', '_', $title));
 $fpath= '/wp-content/themes/YOUR-THEME/images/'.$clean.'.jpg';
 if (file_exists(getcwd() . $fpath)) {
   return "<img src='$fpath' alt='$title' />";
 }
 return $title;
}

add_filter('widget_title', fancy_title);
add_filter('link_category', fancy_title);

Coders Eye - Web Dev Tutorials and How-To Guides for Beginners
Logo
Enable registration in settings - general