Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Devin Gray
Devin Gray
39,261 Points

Remove 'default.png' when my 'featured-image' class doesn't have a thumbnail.

            <?php
                $thumbnail_id = get_post_thumbnail_id();
                $thumbnail_url= wp_get_attachment_image_src($thumbnail_id, 'thumbnail-size', true);
                $thumbnail_meta = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
            ?>

            <p class="featured-image">
                <img src="<?php echo $thumbnail_url[0]; ?>" alt="<?php echo $thumbnail_meta; ?> featured-image project">
            </p>

This code makes sure that it takes whatever my featured image is on my blog and posts it at the top of each blog. The problem is not all of my blogs have featured images. When there is no featured image given to a post, it displays the 'default.png' file at the top of the page. I could always replace the 'default.png' file with something like my logo, but I wanted to know if I could make it so that if my $thumbnail_url variable doesn't have an image, that it just doesn't put anything there altogether. I can't think of how to write the if statement, and since its already inside the loop, will it break if I add another if statement inside it?

Appreciate the help.

1 Answer

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

You can wrap your image output in an if statement that checks if there is a value for the image. You will have to test and play around with it a bit, but something like:

<?php if( $thumbnail_url != ''): ?>

// Your image

<?php endif; ?>
Devin Gray
Devin Gray
39,261 Points

I'll definitely try that. And stay tuned because I'm sure more forum questions are to come as I work on this site for a client.