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!

On WordPress

All things WordPress

    John Morris

    Written by

    I’m a web designer who helps other web designers with two things: 1) how to code and 2) how to market yourself so you can earn your living as a coder.

    On WordPress

    All things WordPress

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade