How to Show Default Image if Featured Image is not Added

The “the_post_thumbnail()” function for featured image in WordPress does not shows anything if a featured image is not attached to the post. In case you want to show a default image in your theme if a user has not attached any featured image then use following script:

<a href="<?php the_permalink(); ?>"> // adds a hyperlink to the image
if ( has_post_thumbnail() ) { //check if featured image is added or not
the_post_thumbnail( ‘medium’, array( ‘class’ => ‘img-responsive’ ) ); //echos featured image if added
else {
<img src="<?php echo get_template_directory_uri(); ?>/images/defaultimg.png" class="img-responsive" alt=""> // outputs default image if not . change the url to match your image.
<?php } ?>

About Author

WP Munk

Leave a Reply

Your email address will not be published. Required fields are marked *