插件与教程

如何在 WordPress 上自动设置特色图片

authorCrazy uncle publish2022-09-14 update2022-09-26 view1,715

最近准备对缩略图做一些调整,决定采用WordPress自带的the_post_thumbnail来实现缩略图的裁剪,不可能再用什么timthumb.php

关于timthumb.php不再支持或维护的介绍:https://code.google.com/archive/p/timthumb/

现在在用的缩略图的特性是需要从WordPress文章里的特色图像来调取裁剪的,而如果每次还要手动去设置一张实在是过于繁琐了,自然是在 WordPress 上自动设置特色图片来得方便很多哈,直接上代码

//自动添加特色图像
function huitheme_auto_set_featured_image() {
   global $post;
   $featured_image_exists = has_post_thumbnail($post->ID);
      if (!$featured_image_exists)  {
         $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', 'huitheme_auto_set_featured_image');

插入到functions.php即可,教程到此结束。

需要说明的是,这个操作是让文章内的图片自动设置一张图片为特色图像的操作,并不是对特色图像或文章内图像进行裁剪并生成缩略图的操作。

有用(9)

这些你同样感兴趣

满足你在每个阶段使用模板的需求,帮助你高效完成工作及任务