Gokul P P Gokul P P - 4 years ago 136
HTML Question

How to set default image, if image is not available in php

I am having a code to show images, but if no image available need to show default image

Currently, I am having this code

<?php ?>
<img src="<?php echo get_the_post_thumbnail_url($post->ID); ?>"/>
<?php ?>

Answer Source

Use has_post_thumbnail() method to check the post have thumbnail and based on that provide default image.

<?php if (has_post_thumbnail()) : ?>
<img src="<?php echo get_the_post_thumbnail_url($post->ID); ?>"/>  
<?php else: ?>
   <!-- default image here -->
<?php endif; ?>

You can use ternary operator to reduce the code.

<img src="<?php echo (has_post_thumbnail() ? get_the_post_thumbnail_url($post->ID) : 'default_image.jpg'); ?>"/>  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download