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 theimages
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.
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.
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/
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?
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/
thank you
[…] This post was mentioned on Twitter by Michael Davis, HTMLfrp. HTMLfrp said: #wordpress Set default the_post_thumbnail http://bit.ly/fe5rS8 […]