X

How To Set a Default Post Thumbnail/Featured Image

Snippets by IsItWP

Are you looking for a way to set a default post thumbnail/featured image? This snippet will check to see if a post thumbnail exists, and if not, it will display a default image named img-default.png.

Instructions:

  • Create a folder called images inside the theme folder.
  • Create an image called img-default.png and place it inside the images folder.
  • Finally, add this code to your theme’s template file inside The Loop.
<?php 
if(has_post_thumbnail()) {
	the_post_thumbnail();
} else {
	echo '<img src="'.get_bloginfo("template_url").'/images/img-default.png" />';
}
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 6 Best Image Optimization Plugins for WordPress (Compared) and how to set up author tracking in WordPress.

Comments   Leave a Reply

  1. Hello,
    I wondering if I can display the post author avatar as the default featured image for posts, rather than a specific image.
    Thank you.

    1. You could, but you would need to set the src value as the URL to the avatar. Or, you could using this function: https://developer.wordpress.org/reference/functions/get_avatar/

  2. Thanks for your post but I don’t understand where I have to put the snippet code. In the function.php o in another template file?

    1. It will need to be another template file, specifically within the Loop. For more about the Loop, check out: https://www.isitwp.com/the-ultimate-guide-to-the-wordpress-loop/

  3. thank you

  4. Tweets that mention Wordpress Set default the_post_thumbnail – wpsnipp.com Wordpress code snippets for your blog -- Topsy.com February 11, 2011 at 4:20 pm

    […] This post was mentioned on Twitter by Michael Davis, HTMLfrp. HTMLfrp said: #wordpress Set default the_post_thumbnail http://bit.ly/fe5rS8 […]

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!