9

How do I get the_tags() to output each tag so that it comes assigned with a unique class selector? So for example: the_tags() currently outputs something like this:

<a href="http://myblog.com/tag/kittens" rel="tag">kittens</a>

However, I'd like to output something like this:

<a href="http://myblog.com/tag/kittens" rel="tag" class="tag-kittens">kittens</a>

Is it possible to do this? If so, how? Thanks!

4 Answers 4

16

It worked, thank you! This is what I did:

<?php
$post_tags = get_the_tags();
if ($post_tags) {
  foreach($post_tags as $tag) {
    echo '<a href="'; echo bloginfo();
    echo '/?tag=' . $tag->slug . '" class="' . $tag->slug . '">' . $tag->name . '</a>';
  }
}
?>
2
  • 5
    You can mark my answer as accepted or yours so other people would benefit when searching for this same problem. You can read how SO works in FAQ. stackoverflow.com/faq
    – GmonC
    Jul 24, 2010 at 2:22
  • Could you post all the code that solves this problem?
    – Р. Р.
    Feb 10, 2022 at 21:25
8

Also you can overload working of get_the_tags(); function. Just add next code to your functions.php theme file:

// add custom class to tag
function add_class_the_tags($html){
    $postid = get_the_ID();
    $html = str_replace('<a','<a class="class-name"',$html);
    return $html;
}
add_filter('the_tags','add_class_the_tags');
1
  • Nice. I like the solution.
    – WordCent
    Oct 9, 2017 at 16:18
3

this code from www.lawturn.com

/* SlSlib tags add class */
<?php if(has_tag()) : ?>

    <?php
    $tags = get_the_tags(get_the_ID());
      foreach($tags as $tag){
        echo '<a href="'.get_tag_link($tag->term_id).'" rel="tag" class="tag-'.$tag->name.'">'.$tag->name.'</a>';
    } ?>

<?php endif; ?>
1

Use get_the_tags instead, do a for loop and create your own markup.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.