Wordpress

How to Save a Default Post Thumbnail

There are many tutorials describing how to check a post for thumbnail and rendering one if there isn’t any. However, I will show you how you can save a post without a thumbnail to begin with.

Step 1: Get a thumbnail ID

First of all, you need to get the ID of the picture you will be using as the default thumbnail. Just upload the picture in the Media Library, select it and collect the ID from the address bar. In this case, the ID is 233.

save a default thumbnail attachment id

Step 2: Code the function

Now that you have the ID, you need to add the following code to your functions.php file:

1.2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

add_action( ‘save_post’, ‘wptuts_save_thumbnail’ ); 

function wptuts_save_thumbnail( $post_id ) {

 

// Get Thumbnail

$post_thumbnail = get_post_meta( $post_id, $key = ‘_thumbnail_id’, $single = true );

 

// Verify that post is not a revision

if ( !wp_is_post_revision( $post_id ) ) {

// Check if Thumbnail exists

if ( empty( $post_thumbnail ) ) {

// Add thumbnail to post

update_post_meta( $post_id, $meta_key = ‘_thumbnail_id’, $meta_value = ‘233’ );

}

}

 

}

The save_post hook is used to activate the function and fetch the last added post. Once that’s done, the get_post_meta function gets the thumbnail ID value from the database. Next, the wp_is_post_revision function checks whether the post is new or a repost. If the function finds that the post is not new, the rest of the function is voided. But if it is new, the if statement checks whether there is any existing thumbnail for the post. If there isn’t, the default thumbnail is added to the recently added post.

save a default thumbnail result

Now, whenever you save a post or publish it, a thumbnail will always be added to it.

About the author

Tabish Shaikh

Website designer, website developer, blogger and a writer. These are the things I like, love and live for. Having years of experience in each field. Developing sites since childhood. Getting the most complicated things done is my specialty. Providing each and everything of top most quality to each and every client.

Leave a Comment


*