WordPress featured image allow you to upload an image inside your dashboard post and pages. The featured image box is usually on the bottom right corner(may be you need to scroll down to see the box when you land to add new page).
Sometimes we don’t have feature image and our area for the feature image remain blank. In this tutorial I am going to show you how we can use conditional statement featured image to fill up the area in the absences of Featured image.

Conditional statement featured image

Copy below code and paste it inside the function.php of your theme folder.


function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];

//no image found display default image instead
   if(empty($first_img)){
   $first_img = "/images/default.jpg";
}
return $first_img;
}

Now go to the loop page where the feature image is displaying.


<figure>
<?php if(has_post_thumbnail() ) { ?>
twentyfifteen_post_thumbnail();
<?php } else { ?>
<a href="<?php the_permalink();?>">
<img src="<?php echo catch_that_image()?>" alt="<?php the_title();?>" />
</a>
<?php } ?>
</figure>

Hope it helps. 🙂
Thank you for reading this article.

Published by Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.