Friday, July 12, 2013

How to Display Image Next To Each Tag in WordPress Website

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

$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 = "http://cdn.css-tricks.com/images/tag-images/$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>';
}
}
}
?>
Disqus Comments