Home / Widgets / Automatically Set Featured Image from First Image in Post
Duplicate Snippet

Embed Snippet on Your Site

Automatically Set Featured Image from First Image in Post

Automatically Set Featured Image from First Image in Post

Code Preview
php
<?php
function auto_set_featured_image() {
    global $post;
    if (!has_post_thumbnail() && $post->post_type == 'post') {
        $attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1");
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID, $attachment_id);
                break;
            }
        }
    }
}
add_action('save_post', 'auto_set_featured_image');

Comments

Add a Comment