WordPress技巧:如何实现文章缩略图
WordPress 缩略图的实现主要靠两种方式,第一种是获取文章中的第一张图片来作为缩略图的图源,第二种是获取文章特色图标来作为缩略图的图源。下面我们将这两种方式结合起来实现 WordPress 缩略图。
第一步,判断文章是否设有特色图片,如果有,则获取特色图片来作为缩略图的图源。
第二步,判断文章中是否存在图片,如果有,则获取文章中第一张图片来来作为缩略图的图源。
第三步,如果既没有设置特色图片,文章也没有图片,则显示默认图片。
具体情况详读代码。
将下列代码放置到主题模版函数 functions.php
中
//缩略图
add_theme_support( 'post-thumbnails' );
function post_thumbnail( $width = 255,$height = 130 ){
global $post;
if( has_post_thumbnail() ){
$timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
$post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$timthumb_src[0].'&h='.$height.'&w='.$width.'&zc=1" alt="'.$post->post_title.'" class="thumb" title="'.get_the_title().'"/>';
echo $post_timthumb;
} else {
$content = $post->post_content;
$defaltthubmnail = sapphire('default-thumb') ? sapphire('default-thumb') : get_template_directory_uri().'/img/no-thumb.png';
preg_match_all('/<img.*?(?: |//t|//r|//n)?src=[/'"]?(.+?)[/'"]?(?:(?: |//t|//r|//n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if($n > 0){
echo '<img src="'.get_bloginfo("template_url").'/timthumb.php?w='.$width.'&h='.$height.'&src='.$strResult[1][0].'" title="'.get_the_title().'" alt="'.get_the_title().'"/>';
} else {
echo '<img src="'.get_bloginfo("template_url").'/timthumb.php?w='.$width.'&h='.$height.'&src='.$defaltthubmnail.'" title="'.get_the_title().'" alt="'.get_the_title().'"/>';
}
}
}
将下列代码放置到需要显示缩略图的地方
<?php post_thumbnail(145,145) ?>
宽度,高度按自己的需求设置。