Dec 11 2008

Delicious for WordPress Plugin – W3C Validation Error: Fixed

I keep almost all my bookmarks at Delicious (formerly del.icio.us.)  So I noticed there is a Wordpress plugin to display your Delicious bookmarks.  One of the things I do after I add a new plugin to WordPress, is to validate a page using The W3C Markup Validate Service.  I noticed that my markup was now invalid, but it wasn’t really because of the plugin itself.  The errors were caused because some of my Delicious bookmarks have predefined ampersand characters, and the plugin did not replace these with HTML entities.  I first tried replacing my bookmark titles in Delicious, but that just screwed up my titles (I always go for the easy way first.)  So it’s time to start editing sources again…

What we need to do to fix this is really quite simple, find the string that stores our bookmark title, and replace the predefined characters with HTML entities.  While looking for the best method to do this using PHP, I found a function that I never knew about before.  There’s actually a nice PHP function to do this: htmlspecialchars()

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.

Perfect, this is what we’re going to use.  So let’s find that string now…

Open delicious.php and go to line 74:

73
74
75
76
77
foreach ( $bookmarks->items as $bookmark ) {
$msg = $bookmark['title'];
if($encode_utf8) utf8_encode($msg);
$link = $bookmark['link'];
$desc = $bookmark['description'];

So we’re going to take line 74 and change it to this:

73
74
75
76
77
foreach ( $bookmarks->items as $bookmark ) {
$msg = htmlspecialchars($bookmark['title']);
if($encode_utf8) utf8_encode($msg);
$link = $bookmark['link'];
$desc = $bookmark['description'];

Quite simple, now we’re back on the right track :)