• Resolved GATEKeeper

    (@gatekeeper)


    I’m looking for a way of building an if/else statement that will display an image if one exists in a theme folder, or display a default image otherwise.

    So, for instance, I have images for some of my tags, but not all of them. I want a piece of script that will check for a file named after the tag slug (or tag ID) and display it. If there’s no image, then it displays some other standard image.

    The closest I’ve come is this code from the WordPress site, but it’s trying to show multiple images because of the “foreach” line. I have no clue what the alternative is. Anyone have some advice?

    Please keep in mind the code will be in the tag.php file.

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
      foreach($posttags as $tag) {
        echo '<img src="https://www.thegate.ca/wp-content/themes/mimbo2.2/tags/' . $tag->term_id . '.jpg"
    alt="' . $tag->name . '" />';
      }
    }
    ?>

    Also, I realize I could create a tag-[slug].php file and call specific images, but I have a lot of tags, so I’d rather not create that many tag files.

    Thanks in advance for any help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter GATEKeeper

    (@gatekeeper)

    Just a little bump for the topic. Anyone have any thoughts? I feel like I’m pretty close to solving this, but I could use the help.

    Thread Starter GATEKeeper

    (@gatekeeper)

    Eureka! I’ve got it.

    Okay, so there may be cleaner ways of doing it, but I messed around until I finally figured it out – I had no idea that $tag was actually something I could use.

    Basically, for the tag page, it checks to see if there’s an image with the tag slug in the specified folder and then outputs that image, or displays a default image.

    <?php
    $image = "$tag.jpg";
    $url = "https://URL TO FOLDER";
    if(file_exists("$url/$image"))
    {
    echo "<img src=\"$url/$image\" alt=\"$tag\" />";
    }
    // if no, give an alternative image
    else
    {
    echo "<img src=\"$url/tag.jpg\" alt=\"$tag\" />";
    }
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Display an image for a tag if it exists in template folder’ is closed to new replies.