How to Set an Attachment as the Featured Image

This handy little snippet sets the first attachment uploaded to a post as the Featured Image


I have clients who like to place their images into the body of their posts and use that same image as the Featured Image.

And, they prefer not to have to set it twice (e.g. http://michaelhyatt.com/10-biggest-goalsetting-mistakes.html)

No problem. Here’s a handy little code snippet that will do just that for you:

// @ http://wp-mix.com/set-attachment-featured-image/
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
global $post;
if (has_post_thumbnail()) {
// display the featured image
$content = the_post_thumbnail() . $content;
} else {
// get & set the featured image
$attachments = get_children(array(
'post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($post->ID, $attachment->ID);
break;
}
// display the featured image
$content = the_post_thumbnail() . $content;
}
}
return $content;
}

I’ve also seen an example using regex, but this version seems to be pretty straight-forward.

If you find value in this snippet, it’d mean a lot to me if you’d hit the “Recommend” button below. Thanks!

Email me when On WordPress publishes stories