cover

WordPress设置文章的第一张图片为特色图片的图文教程

阅读量:1171
评论数量:0
发布时间:2022-11-14 19:02

很多新手刚开始接触WordPress的时候,很多都不懂,每次发布文章都要自己设置特色图片,但是总是感觉操作很麻烦,毕竟自己的一篇文章上传了这么多图片,有没有更好的办法呢,比如设置文章的第一张图片为特色图片。接下来虾皮路就给大家介绍一下WordPress设置文章的第一张图片为特色图片的图文教程。

大家每次写文章的时候是不是发现每次都要设置特色图片很烦呢,如下

image-20221114110008136

其实没有这么复杂,因为每篇文章只要上传了图片都有缩略图,我们都可以调用的,只是调用的方法要修改代码,如下:

首先打开模板文件默认主题下的 functions.php 文件,然后找到最下面,放入如下代码。

/* ------------------------------------------------------------------------- *
* 设置文章第一个图片自动为特色图片
/* ------------------------------------------------------------------------- */
function autoset_featured_image(){
    global $post;
    $already_has_thumb = has_post_thumbnail($post->ID);
    if (!$already_has_thumb){
        $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);
            }
        }
    }
}
add_action('the_post', 'autoset_featured_image');
add_action('save_post', 'autoset_featured_image');
add_action('draft_to_publish', 'autoset_featured_image');
add_action('new_to_publish', 'autoset_featured_image');
add_action('pending_to_publish', 'autoset_featured_image');
add_action('future_to_publish', 'autoset_featured_image');

注意:

如果你手动设置了特色图片,这段代码就不起作用,会默认到你设置的特色图片,无需担心。

评论(0)
暂无评论
logo

诚哥博客是一个专注于分享技术、分享资源的平台,由诚哥打造必属精品,团队有着多年开发经验,专注研究各种前沿技术和资源等服务;并提供有保障的维护及售后

关注我们

关注微信公众号

关注微信公众号

Copyright © 2022-2025 诚哥博客 - 诚哥博客