WordPress自动设置第一张图片为特色图【纯代码】

要在WordPress中自动设置第一张图片为特色图像,你可以通过添加以下代码到你的主题的 functions.php 文件中来实现:

function set_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', 'set_featured_image');
add_action('save_post', 'set_featured_image');
add_action('draft_to_publish', 'set_featured_image');
add_action('new_to_publish', 'set_featured_image');
add_action('pending_to_publish', 'set_featured_image');
add_action('future_to_publish', 'set_featured_image');

 

这段代码会在文章保存、发布或更新时触发,检查文章是否已经设置了特色图像。如果没有设置,则会自动将第一张图片作为特色图像。注意,该代码只会对新发布的文章或更新后未设置特色图像的文章生效。

请确保在修改 functions.php 文件之前备份你的主题文件,并小心操作。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容