Jassar
Jassar

Reputation: 341

replace certain text tags with image tags (icons)

This question was asked 3 years ago

I run a wordpress site, What I want to do is to replace certain text tags with .png images everywhere in the site (home, archives, posts, pages....)

Is there an active plugin for that? If not, what is the simplest way for a beginner to do it?

Thanks a lot.

Upvotes: 0

Views: 617

Answers (1)

Adriano Monecchi
Adriano Monecchi

Reputation: 1200

It'd be great if it was a default WP functionality, however, it's not possible without some hacking. You'd achieve that with the help of a plugin or by writing a custom function.

By starting with get_the_tags() you could extend the code bellow to a custom function and call it anywhere on your .php templates. The following approach implies some manual interventions, such as renaming the image icons for tags with the exact tag-slug and placing them beforehand in a pre-defined directory.

<?php
 $separator ='';
 $output = ''; //initialize clean output;
 $posttags = get_the_tags();
  if ($posttags) {
  $img_path = get_bloginfo('stylesheet_directory');
  foreach($posttags as $tag) {
  $image = 'tag_icon_' . $tag->slug . '.png';

  $link = get_tag_link( $tag->term_id);

  $output .= $separator . '<a href="' . $link . '">';
  $separator =' &nbsp | &nbsp '; // this adds a space between the icons; you can change it
  if(file_exists(STYLESHEETPATH.'/library/images/'.$image)) {
   $output .= '<img src="' . $img_path.'/library/images/'.$image . ' " class="tag_icon" alt="tag ' . $tag->name .' icon" />  '. $tag->name .'  ';
  } else {
  $output .= $tag->name;
  }
 $output .= '</a>';
  }
 echo $output;
  }
 ?>

Adjust /library/images/ to reflect your theme's image directory, and paste the entire code in the loop.

if(file_exists(STYLESHEETPATH.'/library/images/'.$image)) {
  $output .= '<img src="' . $img_path.'/library/images/'.$image . ' " class="tag_icon" alt="tag ' . $tag->name .' icon" />  '. $tag->name .'  ';

Another approach would be trying out a plugin which lets you manage images for tags and categories, but chances you'll find a perfect one for your needs are limited, so you could still extend a plugin's functionality to achieve what you want.

Here's a great article which helped me to build a food menu ingredient's list based on image tags. For each use case you might adjust the tutorial as per your expectations. it helped me out a lot, perhaps you'll find it useful too.

Good Luck.

Upvotes: 1

Related Questions