Apply class to the a tag link generated in post tag links

The function get_the_tags(); is probably what you are looking for. The following code displays a list of tags with links to each one and a specific class for each tag:

<?php
    $tags = get_the_tags();
    $html="<div class="post_tags">";
    foreach ($tags as $tag){
        $tag_link = get_tag_link($tag->term_id);

        $html .= "<a href="https://wordpress.stackexchange.com/questions/57011/{$tag_link}" title="{$tag->name} Tag" class="{$tag->slug}">";
        $html .= "{$tag->name}</a>";
    }
    $html .= '</div>';
    echo $html;
?>

Now, using that logic, I’ve modified your code to do what you want:

<?php if( has_tag() ) { ?>
    <div id="tagWrapper">

        <p>Tags</p>

        <?php
        $tags = get_the_tags();
        $html="<ul class="tags">";
        foreach ($tags as $tag){
            $tag_link = get_tag_link($tag->term_id);
            $html .= "<li class="tag-body olive"><a href="https://wordpress.stackexchange.com/questions/57011/{$tag_link}" title="{$tag->name} Tag" class="{$tag->slug}">";
            $html .= "{$tag->name}</a></li>";
        }
        $html .= '</ul>';
        echo $html;
        ?>

    </div>
<?php } ?>

And the output in case it helps (although untested) should look like this:

<div id="tagWrapper">
    <p>Tags</p>
    <ul class="tags">
        <li class="tag-body olive">
            <a href="http://example.com/tag/technology/" title="Technology Tag" class="technology">Technology</a>
        </li>

        <li class="tag-body olive">
            <a href="http://example.com/tag/gadgets/" title="Gadgets Tag" class="gadgets">Gadgets</a>
        </li>

        <li class="tag-body olive">
            <a href="http://example.com/tag/mobile/" title="Mobile Tag" class="mobile">Mobile</a>
        </li>
    </ul>
</div>

SOURCE: WordPress Codex Function Reference for get_the_tags();

Leave a Comment