boxmoe_header_banner_img

Hello! 欢迎来到盒子萌!

加载中

wordpress懒人写作模式自动设置文章的第一张图为特色图像


avatar
专收爆米花 2018年9月28日 5.2k

主题实际已经设置自动搜索文章第一张图片作为缩略图了,但是有时候图片太大就导致了缩略图也很大,加载反而变慢,又懒得每次手动设置特色图像,所以这段代码可以自动把文章中上传的第一张图片设置为特色图像,缺点就是不支持外链图片

复制代码
  1. function autoset_featured_image() {
  2. global $post;
  3. if (!is_object($post)) return;
  4. $already_has_thumb = has_post_thumbnail($post->ID);
  5. if (!$already_has_thumb) {
  6. $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
  7. if ($attached_image) {
  8. foreach ($attached_image as $attachment_id => $attachment) {
  9. set_post_thumbnail($post->ID, $attachment_id);
  10. }
  11. }
  12. }
  13. }
  14. add_action( 'the_post', 'autoset_featured_image' );
  15. add_action( 'save_post', 'autoset_featured_image' );
  16. add_action( 'draft_to_publish', 'autoset_featured_image' );
  17. add_action( 'new_to_publish', 'autoset_featured_image' );
  18. add_action( 'pending_to_publish', 'autoset_featured_image' );
  19. add_action( 'future_to_publish', 'autoset_featured_image' );


评论(4)

查看评论列表
评论头像
会发光的良辰? 2018年11月03日
嘤嘤嘤
评论头像
专收爆米花 博主 2018年11月04日
嘤嘤嘤嘤
评论头像
tmh 2024年12月09日
在开发一下 缩略图 尺寸代码啊
评论头像
专收爆米花 博主 2024年12月10日
这个wp后台本身可以设置尺寸的啊

发表评论

表情 颜文字
😀😁😂🤣😃😄😅😆😉😊😋😎😍🥰😘😗😙😚😛😝🤗🤔🤨😐😑😶🙄😏😣😥😮🤤😴😪😵😵😵🤯🤠🤡🤥🤫🤔🤨😐😑😶🙄