
WordPress Tags With Custom Title Attribute
Published on November 4, 2012
Every WordPress theme uses the_tags() function to display the tags for the current post, and it works fine. However, it will only display the link with no title and if you need a title attribute you have to make a custom function that uses get_the_tags(). Function below enables you to specify a custom title format when displaying the tags:
functions.phpfunction the_better_tags($title = null){ if(null === $title){ $title = __('More articles tagged with %tag%'); } $tags = get_the_tags(); foreach ($tags as $tag){ $tag_link = get_tag_link($tag->term_id); $html_title = str_replace("%tag%", $tag->name, $title); $html_tags .= "<a href='{$tag_link}' title='{$html_title}'>"; $html_tags .= "{$tag->name}</a>, "; } $html_tags = substr_replace($html_tags,'',-2); echo $html_tags; }
Let's just go through the code quickly. First the function checks if a custom title attribute is specified. If not, "More articles on %tag%" string is used. The %tag% keyword will be replaced with the name of the tag so you can control where the name will appear (or omit it completely). Couple of examples for tag named "Vacation":
- the_better_tags("View more from %tag%") = "View more from Vacation"
- the_better_tags("List of all %tag% articles") = "List of all Vacation articles"
- the_better_tags("Articles on this topic") = "Articles on this topic"
- the_better_tags() = "More articles tagged with Vacation"
Each tag is separated by a coma, but the last coma is removed with the substr_replace function. Use this function just as you would use the_tags() in a theme.
single.php<?php if (has_tag()){ ?> <p class="tags"><?php the_better_tags(); ?></p> <?php } ?>
...or with a custom title format:
single.php<?php if (has_tag()){ ?> <p class="tags"><?php the_better_tags('More like %tag%'); ?></p> <?php } ?>
Using the same principle you can build a new function with your custom HTML output (list, image, whatever you want) or just expand this one and add what you need.
Comments (2)
Vladimir on March 20, 2013
I use next snippet:
<a href="/slug ?>" title="name ?>">
name; ?>
count; ?>
Vladimir on March 20, 2013
code- don’t work..(
<a href="/slug ?>” title=”name ?>”>
name; ?>
count; ?>