How to Set Fallback Image for WordPress Post Thumbnails

Images play an important role in your WordPress posts. When we share the blog on social media, the featured image will display as a thumbnail of your post. These images are helpful to catch the attention of audiences. For some reason, if you don’t have a post thumbnail, you should set a fallback image that acts as a featured image for a post. This fallback image may be the first image from your post content or a default static image.

In this article, we study how to set a default fallback image for WordPress post thumbnails. We will first search for the featured image, if it is not found then we set the first image of post content, and if this also fails then set a default static image.

Set Fallback Image for WordPress Post Thumbnails

For getting started, you should first place the default image in your active theme’s directory. Let’s say your default image name is default.jpg. You can place this file inside the images folder in your theme. Your image path will be ‘wp-content/themes/your-theme-name/images/default.jpg’.

Next, we need to add some pieces of code to the functions.php file. Open the functions.php file and add the below code at the end of the file.

function post_fallback_image() {
    global $post;
    $fallback_image = '';
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $fallback_image = $matches[1][0];
 
    if (empty($fallback_image)) {
        $fallback_image = get_stylesheet_directory_uri(). "/images/default.jpg";
    }
    print '<img src="'. $fallback_image .'" alt="'. get_the_title() .'" class="wp-post-image" />';
}

The above code checks for the first image inside the post content and prints it. If no image is available in the post content then it prints the default static image from the theme directory.

Now to actually use this function we need to find the place to call it. WordPress displays post thumbnails in various places. You may find it in the archive template, post list, or single post page template. We need to find the lines where the_post_thumbnail() function is used in these templates. And then replace this method with the lines below:

<?php
if (has_post_thumbnail()) :
    the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_title() ) );
else :
    post_fallback_image();
endif;
?>

That’s it! I hope you understand how to set a default fallback image for WordPress post thumbnails. Please share your thoughts in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

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