Post Pic

How to define a default post thumbnail

Since version 2.9, WordPress let you define a post thumbnail so you can embellish your post with an image. But there’s no way to define a default thumbnail to be used when no custom thumbnail is defined. Here is a cool recipe to define a default post thumbnail.

Paste the code below into your functions.php file. Don't forget to update the code with your default image url on line 13.

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 = 'http://yoursite.com/your_image_url.jpg' );
		}
	}

}

Thanks to WPTuts for the snippet!

5 Responses

Jul 05 2012 14:16

Great, thanks :D

Jul 05 2012 23:30

Will this save the default thumbnail to the database for posts with no thumbnail?

Jul 10 2012 02:13

For the image URL, could this be a relative URL, e.g. ‘/images/your_image_url.jpg’ ? Or, does it have to be an absolute URL?

Jul 21 2012 13:47

As I understand the _thumbnail_id post meta is supposed to save an integer ID (attachment id), so for update_post_meta shouldn’t we save the attachment id instead of the image url?

Aug 19 2012 17:01

Thanks. I’ve just tweaked it a bit like Sola said.
I’ve defined a constant in my config with the ID of a special image that I’ve uploaded (non attached to a post), and I update the meta with that const in the function.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox