WordPress: if image exists, display it

I’m using this to display a banner image in my WordPress site:

<img src="../../wp-content/uploads/<?php echo get_post_meta($post->ID, 'image-banner', true); ?>" alt="<?php the_title(); ?> banner" />

However, there will be some pages with no banner image.

Read More

How can I rework this check if the image (or ‘image-banner’ field) exists before displaying the img tag?

Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. I think it’s better you use a variable to store img url, so you could just check if it is empty.. Like this:

    <?php
    $imgBanner = get_post_meta($post->ID, 'image-banner', true);
    if (!empty($imgBanner)) {
    ?>
    <img src="../../wp-content/uploads/<?php echo $imgBanner; ?>" alt="<?php the_title(); ?> banner" />
    <?php
    }
    ?>