启用WordPress 缩略图

本文讲清 WordPress 2.9 如何在后台启用文章缩略图,并演示在主题 functions.php 中开…


生猛大蝦 - rendering abstract futuristic background with glowing neon blue orange lights

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 分支,若文章未设置缩略图,就输出一张默认图片作为占位。这样列表页不会出现空白,但要注意默认图尺寸和版式要与主题风格保持一致。


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理。