首页 视频课程 主题开发课程第13章、图片与附件 WordPress自动特色图片实现方法

WordPress自动特色图片实现方法

2023-06-11 / 275阅

在 WordPress 中,可以使用以下代码实现自动提取文章中的第一张图片作为特色图片:

function autoset_featured_image() {
    global $post;
    if (!has_post_thumbnail($post->ID)) {
        $attach_id = false;
        $args = array(
            'numberposts' => 1,
            'order' => 'ASC',
            'post_mime_type' => 'image',
            'post_parent' => $post->ID,
            'post_status' => null,
            'post_type' => 'attachment'
        );
        $attachments = get_children($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                $attach_id = $attachment->ID;
            }
        }
        if ($attach_id) {
            set_post_thumbnail($post->ID, $attach_id);
        }
    }
}
add_action('publish_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'); 

这段代码需要放在主题的 functions.php 文件中。

代码的作用是在文章发布时,检查文章中是否已经设置了特色图片,如果没有,则从文章中提取第一张图片作为特色图片。

你也可以使用插件实现自动设置特色图片的功能,比如 Auto Post Thumbnail。该插件可以在文章发布时自动提取并设置特色图片。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录