How to automatically add first image of post as thumbnail?

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 s

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745353928a4624003.html

相关推荐

  • How to automatically add first image of post as thumbnail?

    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 s

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信