最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to automatically add first image of post as thumbnail?

programmeradmin1浏览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 ?

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 ?

Share Improve this question edited Jul 1, 2019 at 13:12 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Jul 1, 2019 at 10:22 Pierre MétéyéPierre Météyé 1
Add a comment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论