WordPress文章列表页显示缩略图让博客内容更加丰富,美观,那么如何调用WordPress缩略图呢?下面的代码可以帮你实现这个功能,具体效果可见本站首页
特点:
1.判断文章是否设置了特色图像,若有则显示特色图像;
2.若没有特色图像时,查找文章中是否包含图片,若有图片,则调用第一张图片;
3.文章若没有图片则随机调用images/random目录下的一张图片。
第一步:在主题根目录下的functions.php中 添加如下代码:
add_theme_support( 'post-thumbnails' );
第二步:同样在主题根目录下的functions.php中 添加如下代码即可实现自动调用缩略图:
/**
*文章列表页缩略图显示
*
*显示特色图像,或者文章内第一张图片,或者随机显示一张图片
*
**/
function lerm_thumbnail() {
global $post;
if (has_post_thumbnail()) {
// 判断该文章是否已经设置了“特色图像”,如果有则直接显示该特色图像的缩略图
echo '<a class="thumbnail" href="' . get_permalink() . '" title="' . get_the_title() . '">';
the_post_thumbnail();
echo '</a>';
} else { //如果文章没有设置特色图像,则查找文章内是否包含图片
$content = $post->post_content;
preg_match_all('/<img [^>]*src=["|\']([^"|\']+)/i', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if ($n > 0) {
// 如果文章内包含有图片,则取第一张图片的缩略图;
echo '<a class="thumbnail" href="'. get_permalink() .'" rel="bookmark" title="' . get_the_title() . '"><img src="' . $strResult[1][0] . '" alt="' . get_the_title() . '" class="post-thumb"></a>';
}else{
//如果文章内没有图片,则随机显示根目录下images/random文件夹下的一张图片。
echo '<a class="thumbnail" href="the_permalink()" rel="bookmark" title="' . get_the_title() . '"><img src="'.get_template_directory_uri().'/images/random/'.rand(1,10).'.jpg" alt="' . get_the_title() . '" class="post-thumb"></a>';
}
}
}
第三步:主题根目录下images文件夹中新建random文件夹,然后在里面放10张.jpg的图片即可;
第四步:若想在博客中显示一张默认的图片,则将
<img src="'.get_template_directory_uri().'/images/random/'.rand(1,10).'.jpg" alt="' . get_the_title() . '" class="post-thumb">
这句中的'.rand(1,10).'
改成想要显示的默认图片即可。
若有好的想法或者建议,请在下方评论区留言评论。