WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following code in attempt to check for an image before an echo. The reason for doing so is if there is no image it won't echo anything and there won't be a missing image link put in a post that has no image. However this code does not work and when no image exists a missing image icon is added. Is there another way to solve this.

<?php $image = wp_get_attachment_image_src(get_field('post_image1'), 'thumbnail'); ?>
        <img src="<?php if($image !=false) echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image1')) ?>" />
        <?php $image = wp_get_attachment_image_src(get_field('post_image2'), 'thumbnail'); ?>
        <img src="<?php if($image !=false) echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image2')) ?>" />
share|improve this question
up vote 2 down vote accepted

wrap the html output in the conditional like this:

 <?php $image = wp_get_attachment_image_src(get_field('post_image1'), 'thumbnail');
 if( $image !=false ) {  ?>
    <img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image1')) ?>" />
 <?php }
 $image = wp_get_attachment_image_src(get_field('post_image2'), 'thumbnail'); 
 if( $image !=false ) {  ?>
    <img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image2')) ?>" />
 <?php } ?>
share|improve this answer

put the if($image !=false) statment before <img> tag so that it'll check if $image is not null before printing out the <img> tag.

Here is sample code

    $image = wp_get_attachment_image_src(get_field('post_image1'), 'thumbnail'); 
    if($image !=false) { ?>
    <img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image1')) ?>" />
<?php } ?>
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.