How to display a default post thumbnail in WordPress without setting featured image for every post

Do you have a WordPress theme which displays post images on the blog index page, but some of the posts do not have image and break the layout? This is a common issue and once the WordPress website is launched … Continued

Do you have a WordPress theme which displays post images on the blog index page, but some of the posts do not have image and break the layout?

This is a common issue and once the WordPress website is launched and the client takes it over, there is no guarantee that they will upload a featured image to every blog post, doesn’t matter how many times you told them to do so. Depending on the theme it may make things look ugly when a few posts pop up without featured image.

One possible solution is to use a plugin which attaches a default featured image to every new post, but this solution is a little bit clunky – if you ever need to change default image, you will need to do a bulk update of all posts overriding default image while preserving user’s set images. Plus it makes it a bit confusing at admin’s end as all posts will be officially having a featured image and there is no easy way to tell which one is real and which one is attached by a plugin.

Another option is to modify theme and every time the featured image is used, call has_post_thumbnail(), then use an alternative code if functions returns “false”, which means post doesn’t have an image. This is a good approach, but you may need to spend some time chasing all featured images calls, which may be not an easy thing to do especially if you are working with an existing theme. Plus, some plugins may use featured image (e.g. latest posts or related/popular posts plugins) and that makes things really hard to deal with.

This solution allows you to setup default thumbnail image in the WordPress theme customizer and this image will be shown everywhere featured image is used, as long as code uses the_post_thumbnail() function to generate featured image’s code. Which means, it will work with most themes and plugins. Unfortunately, if theme or plugin authors used custom code to generate image’s markup, we are out of luck. In that case you can still use this code to setup default post image in customizer, but then you will need to alter theme code and add a conditional get_option('default_post_thumbnail_id') to fetch default post ID and pass it to the theme.

To try this solution follow those steps:

  1. Insert the code into the “functions.php” file of your theme.
  2. Go to the WordPress theme customizer  (WP Admin Dashboard -> Appearance -> Customize).
  3. Upload a default image to the “Default Thumbnail” section.

Leave a Reply

Learning WordPress development?

Subscribe and never miss a post about WordPress themes and plugins coding techniques, WordPress website development workflow and best practices.