Grow your CSS skills. Land your dream job.

Last updated on:

Display Image Next To Each Tag

$posttags = get_the_tags(); // Get articles tags
$home = get_bloginfo('url'); // Get homepage URL

// Check tagslug.png exists and display it
if ($posttags) {
 foreach($posttags as $tag) {
       $image = "$tag->slug.png";

       if (file_exists("images/tag-images/$tag->slug.png")) {
         echo '<a href="' . $home . '/tag/' . $tag->slug . '" /><img title="' . $tag->name . '" alt="' . $tag->name . '" src="' . $image . '" /></a>';

       // If no image found, output something else, possibly nothing.
       } else {
         echo '<p>Not found</p>';

This code belongs inside the loop. It will look in a specific directory for any images that match the slugs of article tags, display them and link them to the relevant tag archive.


  1. TeMc
    Permalink to comment#

    Is there a reason you’re not using $image in the file_exists-call ?

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".