Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

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

<?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 } ?>
share|improve this answer

Your Answer

 
discard

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.