您想在博文上自动设置精选图片吗?有时,您没有帖子的精选图像,并且您希望自动将文章的第一张图像用作精选图像。

将以下代码段添加到WordPress主题的functions.php文件中,以自动为帖子设置精选图像。

 

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

 

如果您将精选图片添加到帖子中,则会覆盖此代码并显示您的精选图片。

我们希望此代码可以帮助您自动为帖子设置精选图片。您可能还想查看有关删除精选图片元框的指南。


送福利了!关注下方的公众号:“优派编程”,搜索关键词“下载”,即可获得软件app下载资源和python、java等编程学习资料~ 更多课程和学习资料请登录“方包博客”———http://fang1688.cn

更多资源请关注公众号或点击下方“阅读原文”,回复关键词获取

发表评论

您的电子邮箱地址不会被公开。

+ 70 = 74