Replacing WordPress’ the_category() Function for HTML5 Compliance

I’ve been working on developing a WordPress theme framework which I intend to use primarily for my own development (ie, to save time and effort, therefore leaving me more time to put fancy bells and whistles on my clients’ sites vs. always programming out the same code with every project). Even though I don’t think I’ll release the extremely bare bones theme on, I wanted to make sure the theme met with WP’s best practices. Therefore, I’ve been using the Theme Check plugin and also following the Theme Guidelines.

I wanted to comply with everything in the guidelines, though at some point I may digress to suit my own development needs vs. just a blanket set of WordPress standards. That’s where I ran into an issue: the_category() outputs invalid HTML. According to the Guidelines:

Themes must not generate any WordPress deprecated-function notices, PHP errors, warnings, or notices, HTML/CSS validation errors, or JavaScript errors.

But the_category() outputs the following by default:

<a href="" title="View all posts in CategoryName" rel="category">CategoryName</a>

rel="category" doesn’t pass validation. According to the HTML5 Validator on the

Bad value category for attribute rel on element a: Not an absolute IRI. The string category is not a registered keyword or absolute URL.

So How Can We Fix This?

Let’s recreate the_category() in our functions.php file.

// Create a function to output valid category links
function the_category_valid() {
$categories = get_the_category();
$separator = ', ';
$output = '';
foreach($categories as $category) {
$output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
echo trim($output, $separator);

Then, in our theme we’ll simply replace the the_category() function with the_category_valid().


Up Next: More Fun with User Agent Strings and WordPress Conditional Tags for Mobile Devices