Site icon StartFunction

Output each WordPress tag with a specific class

You might be familiar with sites like Dribbble or Creattica where they show, along with the usual text tag, another tag which is simply a coloured rectangle for Dribbble or a square in Creattica. Not only do they look good but they are an effective interface element. In this tutorial we will learn how to output the tags of a post with specific classes for each tag using WordPress.

Locate the place where your theme outputs the tags for your post and replace it or combine it with the following code:

[php]
$posttags = get_the_tags();
if($posttags){

$customtags = "<div class=’tags’>";
foreach ($posttags as $tag) {
$customtags .= "<a class='{$tag->slug}’
title=’" . ucwords($tag->name) . "’
href=’" . get_tag_link($tag->term_id) . "’>" ;
$customtags .= "{$tag->name}</a>n";
}
$customtags .= "</div>";

echo $customtags;
}
[/php]

Let’s go through each line. The first one initializes a $posttags variable where we will store all our tags. After checking that we actually have some tags, we start a foreach loop retrieving the tags currently assigned to the post to iterate through each one.

The third line outputs a tag. After opening an anchor, its class attribute is set to $tag->slug which will output the tag slug for your class, so if your tag name is Light Blue, the slug will be light-blue.

Next, we write the title attribute for the anchor simply embedding $tag->name . I’ve added the ucwords PHP function to capitalize the first character of each word that your tag is composed of in case you forgot when you first wrote your tag name. In this way all names will be consistent. If you want all lowercase numbers just remove this function.

Finally, we write the link for the tag and in the next line we close our anchor, not before adding the tag name again (I didn’t added the ucwords function here for the sake of explaining how would you write it instead).

We now only have to close the wrapping div and echo our $customtags variable, which now contains our tags with specific classes for each one of them. Now you can style each tag selecting them using the proper class.

Exit mobile version