Colorful WordPress Tags

home | blog | Colorful WordPress Tags

The goal today is to get the tags on my wordpress posts to look like this:

My guidelines are:

It’s a very simple php bit I added to my front-page.php file, because that’s where I wanted it to show.

  <?php
    // Define tag name to CSS class mappings
    $tag_class_map = array(
        'Git' => 'git-tag',
        'php' => 'php-tag',
        'wp' => 'wp-tag',
        'css' => 'css-tag',
        'js' => 'js-tag'
    );

    // Check if there are any tags for the current post
    $tags = get_the_tags();
    if ($tags) {
        echo '<ul class="tag-list">';
        foreach ($tags as $tag) {
            // Default CSS class
            $tag_classes = 'code';

            // Check if the tag name exists in the mapping
            if (isset($tag_class_map[$tag->name])) {
                // Assign corresponding CSS class
                $tag_classes = $tag_class_map[$tag->name];
            }

            echo '<li class="' . $tag_classes . '"><a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a></li>';
        }
        echo '</ul>';
    }
?>

I think it looks very nice and organized and I’ve kept the default wordpress settings, meaning the user can click on a tag and use it as a filter.

Another way of setting these, would be using Javascript. I think it’s longer and messier and, in general, I prefer the PHP solution, but here’s the Javacript version:

<ul id="tag-list" class="tag-list">
    <!-- Tags will be dynamically added here -->
</ul>

<script>
    // Define tag name to CSS class mappings
    var tagClassMap = {
        'Git': 'git-tag',
        'php': 'php-tag',
        'wp': 'wp-tag',
        'css': 'css-tag',
        'js': 'js-tag'
    };

    // Function to add tags dynamically
    function addTag(tag) {
        var tagList = document.getElementById('tag-list');
        var tagClasses = tagClassMap[tag.name] || 'code'; // Default to 'code' if no matching CSS class found
        var listItem = document.createElement('li');
        listItem.className = tagClasses;
        var link = document.createElement('a');
        link.href = getTagLink(tag.term_id); // Assuming getTagLink function is defined elsewhere
        link.textContent = tag.name;
        listItem.appendChild(link);
        tagList.appendChild(listItem);
    }

    // Assuming you have an array of tag objects 'tags'
    var tags = [
        { name: 'Git', term_id: 1 },
        { name: 'php', term_id: 2 },
        { name: 'css', term_id: 3 },
        { name: 'html', term_id: 4 } // An example tag with no mapping, defaults to 'code'
    ];

    // Add each tag dynamically
    tags.forEach(function(tag) {
        addTag(tag);
    });
</script>

See you next time,

Michele

By on Feb 19th, 2024 in Code

Leave a Reply

Your email address will not be published. Required fields are marked *

Continue reading »