Site icon Hip-Hop Website Design and Development

Programmatically Set First Picture as Featured

I’ve over 400 posts with photos inside them, I’ve obtained a brand new template which requires a featured picture for every put up, one thing my final template didn’t require… I’m questioning if there’s a script I can add to my capabilities.php to have the ability to seize the primary picture in every put up and set it because the featured… To date i’ve discovered this, however it isn’t working…

perform auto_set_featured() {
world $put up;
$has_thumb = has_post_thumbnail($post->ID);
if (!$has_thumb)  {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=picture&numberposts=1" );
    if ($attached_image) {
        foreach ($attached_image as $attachment_id => $attachment) {
            set_post_thumbnail($post->ID, $attachment_id);
        }
    }
}
}
add_action('the_post', 'auto_set_featured');
add_action('save_post', 'auto_set_featured');
add_action('draft_to_publish', 'auto_set_featured');
add_action('new_to_publish', 'auto_set_featured');
add_action('pending_to_publish', 'auto_set_featured');
add_action('future_to_publish', 'auto_set_featured');

This script will work for brand new posts, however i would like it to have an effect on all my older posts, any options?