0

Lot of subject talk about it but seem to be outdated.

I use the new version of Wordpress (5.2.2), and no plugin or code snippet working.

Someone already has this problem ?

I already use plugin the Auto Post Thumbnail, and it's not working. Do you know a plugin for that ?

0

Please try the code given below:

    function auto_featured_image() {
    global $post;

    if (!has_post_thumbnail($post->ID)) {
        $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);
            }
        }
    }
}
// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');
// Used for new posts
add_action('save_post', 'auto_featured_image');
add_action('draft_to_publish', 'auto_featured_image');
add_action('new_to_publish', 'auto_featured_image');
add_action('pending_to_publish', 'auto_featured_image');
add_action('future_to_publish', 'auto_featured_image');

I have tested this code in WordPress 5.2.2

4
  • This will only work if the first image in the post is attached to the post already, which is not guaranteed, since they could be an image that was already uploaded, or an external image. – Jacob Peattie Jul 1 '19 at 10:37
  • @JacobPeattie Yes, this will not work for the external image but if you have added an image in a post content from the editor from wordpress media then it will set as a featured image. – Bhupen Jul 1 '19 at 10:41
  • No, as Jacob mentioned, get_children() will only get an image if it is actually attached to the post - meaning it was uploaded from that post screen. Any other images embedded in post_content will be ignored. A regex to go through the post content might be more efficient, though you'd also need to take both editors into account. – WebElaine Jul 1 '19 at 13:31
  • Your code effectively work if I drag and drop the image directly in the post. But If I add the image from Wordpress Media, it doesn't work. – Pierre Météyé Jul 2 '19 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.