自动提取 WordPress 文章中的第一张图片作为文章缩略图

文 / @WordPress主题

如何利用WordPress缩略图系统优化网站图片

我是一个喜欢在网站中使用图片的小本本,然而,如果不注意图片的尺寸和大小,就可能会让网站变得缓慢。幸好,WordPress内置了一个强大的缩略图系统,可以自动输出压缩后的图片,保证网站打开速度。

如何让文章自动提取第一张图片作为缩略图

有时候,我们在文章中上传图片,但却忘记了上传缩略图,导致某些主题显示不正常。这时可以利用以下代码,自动提取文章中第一张图片作为缩略图。

代码实现思路:首先判断是否为自动保存的修订版本,然后判断当前编辑的是否为文章,最后判断是否手动设置了缩略图。如果不是,就调取文章附件中的第一张图片,设置为文章的缩略图。


function zhiku_automatic_featured_image($post_id){
    if(wp_is_post_revision($post_id))
        return NULL;

    if(!isset($post_id))
        return NULL;
    if(has_post_thumbnail($post_id))
        return NULL;

    $args = array(
        'numberposts' => 1,
        'order' => 'DESC',//DESC for the last image
        'post_mime_type' => 'image',
        'post_parent' => $post_id,
        'post_status' => NULL,
        'post_type' => 'attachment'
    );

    $attached_image = get_children($args);
    if($attached_image){
        foreach($attached_image as $attachment_id => $attachment)
            set_post_thumbnail($post_id, $attachment_id);
    }
}
add_action('save_post', 'zhiku_automatic_featured_image');

有了这段代码,不仅可以保证主题显示正常,还能省去手动设置缩略图的步骤,实现一举两得。

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。