WordPress and HTML validation

WordPress and HTML validation

Some practical tips to validate your WordPress site.

I stumbled on some problems during the validation process of this site. All errors were quite simple to understand, but still they did need a proper treatment (so to speak). In this post I'd like to show you how I managed to successfully validate this site.

Bad rel attribute values

WordPress adds a lot of custom values to the rel attribute of links, especially on categories. Here's the fix:

function remove_category_list_rel($output) {
  $output = str_replace(' rel="category tag"', '', $output);
  return $output;
}
add_filter('wp_list_categories', 'remove_category_list_rel');
add_filter('the_category', 'remove_category_list_rel');

By doing so, you actually prevent WordPress from generating values that are not valid.

Social buttons

If you want to use iframes for your social buttons, you should take into account the following criteria:

  1. The & separator must be written as &
  2. URI components must be properly encoded.
  3. You can't use obsolete attributes, such as frameborder.

Here's how you can properly encode URI components:

function encodeURIComponent($str) {
    $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
    return strtr(rawurlencode($str), $revert);
}

Point 3 is more complicated. Actually, you can't handle the visual appearance of your iframes only with CSS, because some default behaviors can't be overridden. So you have to cheat the validator:

if(!stristr($_SERVER['HTTP_USER_AGENT'], 'validator')) {

			$border = ' frameborder="0"';

}

Here's the complete code:

function tweet_button($layout = 'vertical', $via = 'gabromanato') {

	$title = get_the_title();
	$link = get_permalink();
	$border = '';
	
	if(!stristr($_SERVER['HTTP_USER_AGENT'], 'validator')) {

			$border = ' frameborder="0"';

	}
	
	if($layout != 'vertical') {
	
		$html = '<iframe' . $border . ' src="http://platform.twitter.com/widgets/tweet_button.html?';
		$html .= 'url=' . $link . '&text=' . encodeURIComponent($title) . '&count=' . $layout . '&via=' . $via . '" style="width: 130px; height: 20px;"></iframe>';
	
	
	} else {
	
		$html = '<iframe' . $border . ' src="http://platform.twitter.com/widgets/tweet_button.html?';
		$html .= 'url=' . $link . '&text=' . encodeURIComponent($title) . '&count=' . $layout . '&via=' . $via . '" style="width: 70px; height: 70px; overflow: hidden;"></iframe>';
	
	}
	
	return $html;

}

Yes, it's not 100% politically correct but until browsers won't let you to stylize iframes properly, there's no other way if you want to use them.