how to: add individual css classes to sidebar widgets in wordpress using widget logic

how to: add individual css classes to sidebar widgets in wordpress using widget logic there are some wordpress themes which, for some reason, remove the individual widget wrap css-classes, and just add one generic class to all the widgets, e.g.
<div class="widgetwrap"> ... </div>

this is a real pain if you want to change the appearance of just one specific widget in your sidebar.
at the same time, widget logic is (1) a very powerful widget plugin, and (2) known to have incompatibilities with some other widget plugins (or is it the other way round?).

to solve this problem while keeping widget logic, i wrote a little script and thought i’d share.


just add this to the bottom of your theme’s functions.php:
//widget logic filter to add individual widget classes
 
add_filter('widget_content', 'widgetclasschanger');
function widgetclasschanger($content='',$widget_id='')
{
//read widget title
preg_match("/<h5[^>]*>([^<]+)/",$content, $matches);
$widgetname=substr(str_replace(" ","",strtolower($matches[1])),0,7);
if($widgetname=="") { $widgetname="anonymo"; }
 
//append classes
preg_match("/<div class\=\"([^\"]*)\"/",$content, $matches);
$content=preg_replace("/<div class\=\"([^\"]*)\"/","<div class=\"$1 wid-$widgetname\"",$content,1);
return $content;
}

then go to your appearance – widgets, scroll down all the way to the bottom and activate “Use ‘widget_content’ filter”. you may replace the “7” with any number of characters that should be taken from the title. i limited it in order to prevent a special character mess)
et voilá!
you can now use css-classes that correspond to your widget titles.

(solution tested and working with wordpress 3.3.1 and widget logic 0.51, can’t make any prognosis for other versions)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.