如何自动添加帖子的第一张图片作为缩略图?

时间:2019-07-01 作者:Pierre Météyé

很多话题都在谈论它,但似乎已经过时了。

我使用新版本的Wordpress(5.2.2),没有插件或代码片段。

有人已经有这个问题了?

我已经使用了插件自动张贴缩略图,但它不起作用。你知道这方面的插件吗?

1 个回复
SO网友:Bhupen

请尝试以下代码:

    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\');
我已经在WordPress 5.2.2中测试了此代码

相关推荐