Skip to content

WordPress: how to add specific classes to the_tags()

A simple approach at injecting custom classes into the generated taglist HTML, with code and explanation.

WordPress has a tagging system for adding tags to posts. This is a good system for linking content with similar terms. WordPress also offers a presentation function the_tags() for displaying a list of tags associated with a post as a series of links.

This can be used to list the tags as shown below:

a depiction of a blog index with post headings and a list of respective tag links under each heading.

And this is a sample of the generated link for the HTML tag.

<a href="https://planetjon.ca/tag/html/" rel="tag">HTML</a>

The generated HTML is fine, but if we want to customize the style of particular tags, there are no identifying classes. We could use a CSS attribute selector such as [href$="html/"] but this isn’t aligned with how WordPress generates tag classes, such as “tag-html” in the body element when viewing the tag page for the HTML term.

Here’s how to inject classes into the generated output.

add_filter( 'term_links-post_tag', function( array $links ) {
  return preg_replace_callback(
    '|href="[^"]*/([^"]+?)/?"|',
    function( array $matches ) {
      list( $href, $slug ) = $matches;
      return "class=\"tag-{$slug}\" {$href}";
    },
    $links
  );
});

We hook into term_links-{$taxonomy} and use a Regular Expression to extract the tag slug from the URL. The slug is used to build up and inject a class name.

This method will have some relative overhead, but if your site pages are being cached, then this is acceptable. Ideally, WordPress will offer better hooks for lending to this kind of enhancement.

Now that we have our tag list with classes, below is an example of what is possible.

a depiction of a blog index with post headings and a list of respective tag links under each heading. Key tags such as HTML, PHP, are styled to the brand colours.

And this is a sample of the generated link for the HTML tag, now with a tag-html class.

<a class="tag-html" href="https://planetjon.ca/tag/html/" rel="tag">HTML</a>