1. Code
  2. WordPress

Quick Tip: Saving a Default Post Thumbnail

Scroll to top
Read Time: 2 min

This tutorial will demonstrate how to create a Default Post Thumbnail from the core. Many tutorials demonstrate how to check if a thumbnail exists in a post and then render one if no thumbnail exists. This tutorial will show you how to avoid saving a post without a thumbnail, in the first place.

Usual Way to Get Default Thumbnail

As mentioned before, some tutorials suggest making an If ... Else statement in the theme to show a default thumbnail. An example is as follows:

That simple statement will work, but it would require modifying third-party plugins that do not have default thumbnail features. Which is why, this tutorial will save a default thumbnail to the database.

Step 1 Getting the Thumbnail ID

The first thing you have to do is fetch the ID of the uploaded thumbnail you will be using. You do this by visiting the Media Library, selecting your image, and collecting the ID.

In the screenshot, one collects the ID integer from the address bar where "attachment_id=".

Step 2 Coding the Function

To add the default thumbnail feature, you can add the following snippet to your functions.php file in your theme folder.

We use the save_post hook to trigger our function and get the recently added post. Once we are referencing the recently added post, we use get_post_meta to get the value from the database for thumbnail ID where the post ID is the last inserted. Next we use the wp_is_post_revision function to check whether the saved post is a revision or a new post. If the post is a revision, then we will void the rest of the function. Using an If statement, we check to see if any meta data for the thumbnail exists. If none exists, then we use the add_post_meta function to add the default thumbnail's ID to the last inserted post.

Voila! During a save on draft save, the default thumbnail will be saved to the database and is now available for use in Widgets or Plugins that use thumbnails. If you are building a theme, you can use this method and replace the $meta_value with an image from your theme file. Happy Coding!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.