# 启用WordPress 缩略图

- Link: https://yjyj.net/learn/wordpress-learn/1618.html
- Published: 2010-12-24T06:33:00+08:00
- Author: 小 虾

⚡ 生猛大蝦编辑部 · 30 秒核心看点

 * 在主题 functions.php 里加上 post-thumbnails 支持，后台编辑页就会出现缩略图选项。
 * 前台可用 has_post_thumbnail() 判断，再用 the_post_thumbnail() 输出指定尺寸和 
   class。
 * 没有特色图时可用默认图片兜底，但每篇文章仍需手动设置缩略图，维护成本要注意。

WordPress 2.9已经内置了缩略图的功能，但是却在后台编辑页面没有直接启用。那如何在WordPress
2.9后台启用缩略图的功能呢？方法很简单

，就是在你所用的主题的functions.php文件中添加：

> if ( function_exists( ‘add_theme_support’ ) ) { 
> add_theme_support( ‘post-thumbnails’);}

添加完这个以后，你重新刷新新建文档的页面，是不是在侧边栏已经出现了缩略图的选择了。
剩下的就是，如何调用文章的缩略图啦。我们以index.php为例，将index.php中下面的代码：

> <div class="entry"> 
> <?php the_content(‘Read the rest of this entry &raquo;’);?
> > </div>

修改为：

> <div class="entry"> 
> <?php if ( has_post_thumbnail() ) : ?> <?php the_post_thumbnail(
> array( 125, 125 ), array( ‘class’ => ‘alignleft’ ) ); ?> <?php endif; ?> <?php
> the_content(‘Read the rest of this entry &raquo;’); ?> </div>

其中，arry(125, 125)是说缩略图的大小，同样也可以根据后台的设置，指定为thumbnail、
medium、large或者full。 
至于array( ‘class’ => ‘alignleft’ )，指定的就是图片的class
效果了。

进一步的，如果这篇文章没有图，那么我们怎么显示一张默认的图片(例子.jpg)呢？

> <?php if ( has_post_thumbnail() ) : ?> 
> <?php the_post_thumbnail( array( ‘thumbnail’),
> array( ‘class’ => ‘alignleft’ ) ); ?> <?php else : ?>     <img src="例子.jpg" /
> > <?php endif; ?>

缺点就是需要手动设置每一篇文章的缩略图

❓ 延伸问答与排错指南（FAQ）

WordPress 2.9怎么开启文章缩略图？

在当前主题的 functions.php 中加入 add_theme_support('post-thumbnails') 即可。保存
后刷新后台新建文章页面，侧边栏通常就会出现缩略图设置区域，之后就能为文章单独指定
特色图。

前台模板里怎么调用文章缩略图？

先用 has_post_thumbnail() 判断是否存在缩略图，再用 the_post_thumbnail() 输出。可以
指定尺寸数组和 class，例如让图片以左浮动显示，适合文章列表页或首页摘要区直接展示
封面。

没有缩略图时如何显示默认图片？

可以在判断语句里加 else 分支，若文章未设置缩略图，就输出一张默认图片作为占位。这样
列表页不会出现空白，但要注意默认图尺寸和版式要与主题风格保持一致。

📚 【[WordPress 学习](https://yjyj.net/category/learn/wordpress-learn)】专栏延伸
阅读与热门精选（[全站文章归档](https://yjyj.net/archive)）：

 * [WordPress自动升级超时Operation timed out after 30 解决方案](https://yjyj.net/learn/wordpress-learn/1181.html)
 * [IIS下不用Rewrite实现wordpress伪静态](https://yjyj.net/learn/wordpress-learn/1102.html)
 * [禁用wordpress自动保存和修订版本的几种方法](https://yjyj.net/learn/wordpress-learn/1623.html)
 * [wordpress出现奇怪问题”过期预发布”](https://yjyj.net/learn/wordpress-learn/1640.html)
 * 热门必读[Shopify Sessions 数据维度表](https://yjyj.net/learn/shopify/7764.html)
 * 热门必读[解决: windows 环境下 无法将“git”项识别为 cmdlet、函数、脚本文件或可运行程序的名称](https://yjyj.net/learn/7776.html)
