Wordpress has really come a long way since I first started using it back when it was version 1.0. It now has a nice clean admin interface (although I am currently using the tiger style admin), a clean and simple installation script, and my new favorites, dynamic sidebars and widgets. However, I noticed that the default links widget creates invalid XHTML markup. After a few minutes of looking through the XHTML and widgets.php file, I realized that the culprit was in fact a core wordpress bug. Currently, wordpress creates widgets with the following code:

1
'before_widget' => '<li id="%1$s" class="widget %2$s">',

This has the nasty effect of creating widget wrappers according to their widget name due to the “%1$s”, which isn’t a deal until you actually have multiple instances of the same widget; in my case, the links widget. Having figured out the problem, I began searching for solutions online and stumbled upon the actual Wordpress bug report in trac. The proposed solution was to add the following line of code before the call to wp_list_bookmarks() in wp_widget_links():

1
$before_widget = preg_replace('/id="[^"]*"/','id="%id"', $before_widget);

Unfortunately, this solution wasn’t good enough for me because I didn’t want to have to remember this in case the next Wordpress release didn’t fix the bug. So, after some quick thinking I came up with the following bit of code that can be added to any theme’s function.php file (I think, I am a bit new to Wordpress widgets, in fact, this will be my first).

Edit: This code is actually the exact copy of the widget_links code that ships with wordpress in the widget.php file. All I did was add the previous fix and moved it into functions.php to create a custom widget.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function widget_my_links($args) {
global $wp_db_version;
extract($args, EXTR_SKIP);
if ( $wp_db_version < 3582 ) {
// This ONLY works with li/h2 sidebars.
get_links_list();
} else {
$before_widget = preg_replace('/id="[^"]*"/','id="%id"', $before_widget);
wp_list_bookmarks(array(
'title_before' => $before_title, 'title_after' => $after_title,
'category_before' => $before_widget, 'category_after' => $after_widget,
'show_images' => true, 'class' => 'linkcat widget'
));
}
}
if ( function_exists('register_sidebar_widget') )
register_sidebar_widget(__('My Links'), 'widget_my_links');

This should add a custom widget called ‘My Links’ when you view the Presentation -> Widgets menu. Replace your current Links Widget with this one, and you should be set to go. No more invalid markup, at least not from the links widget.