First Image as Featured ... when featured was not set

Funesto

New member
May 11, 2019
29
8
3
Hello!
Is there a plug-in setting first article image as featured ... but ONLY if a feauted was not manually set?

Sometimes I forget to set a featured image and in that case I'd like the plug in to do it for me, picking from the first image in article. But this only if I did not already set it by myself!

Any suggetsions?

Thank you so much!

G.
 

mrskt

New member
Oct 15, 2022
1
0
1
You can add this code in your theme's functions.php file instead of a plugin:
PHP:
function set_first_image_as_featured($post_id) {
    $post = get_post($post_id);

    // Check if a featured image is already set
    if (has_post_thumbnail($post_id)) {
        return;
    }

    // Get the first image from the post content
    $first_image = '';
    $matches = array();
    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $post->post_content, $matches);
    if (isset($matches['src'])) {
        $first_image = $matches['src'];
    }

    // If a first image is found, set it as the featured image
    if (!empty($first_image)) {
        $attachment_id = attachment_url_to_postid($first_image);
        if ($attachment_id) {
            set_post_thumbnail($post_id, $attachment_id);
        }
    }
}

add_action('save_post', 'set_first_image_as_featured');

And for existing posts, you can add this one time code and after that refresh your wp dashboard and then remove this code:

PHP:
function set_featured_images_for_existing_posts() {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1, // set the number of posts per page to -1 to get all posts
    );
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            set_first_image_as_featured(get_the_ID());
        }
        wp_reset_postdata();
    }
}
add_action('init', 'set_featured_images_for_existing_posts');
 

Funesto

New member
May 11, 2019
29
8
3
Hello!
Is there a plug-in setting first article image as featured ... but ONLY if a feauted was not manually set?

Sometimes I forget to set a featured image and in that case I'd like the plug in to do it for me, picking from the first image in article. But this only if I did not already set it by myself!

Any suggetsions?

Thank you so much!

G.
Hey Thank you so much! :)
 

Funesto

New member
May 11, 2019
29
8
3
Becouse of my VERY CHEAP hosting I had to remove the code for existing post ... It was always "Error 500". Anyway .. Now I am sure my next post won't miss featured image! Thanks again! :)
 

Latest posts

Forum statistics

Threads
66,797
Messages
892,818
Members
217,026
Latest member
gximh1

About us

  • Our community has been around for many years and pride ourselves on offering unbiased, critical discussion among people of all different backgrounds. We are working every day to make sure our community is one of the best.

Quick Navigation

User Menu