How to set featured image to a post automatically in WordPress

If you are finding a solution to set featured image automatically in WordPress, these following code lines will help you save several minutes.

The action blow only supports setting featured image on updating a post.

The function first check if a post already has featured image. If not, it queries all images uploaded to the post and set the first uploaded image as featured one.

function my_plugin_set_feature($post_id) {
	if (!has_post_thumbnail($post_id))  {
		$attached_images = get_children("post_parent=$post_id&post_type=attachment&post_mime_type=image&numberposts=1" );
		if ($attached_images) {
			foreach ($attached_images as $attachment_id => $attachment) {
				set_post_thumbnail($post_id, $attachment_id);
				break;
			}
		}
	}
}
add_action('save_post', 'my_plugin_set_feature');

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close