现在的wordpress主题大多都集成了首页和列表页自动调用文章内第一张图片作为缩略图进行展示的功能,文内没有图片的话也会显示随机图片,以提高用户体验度。晓兔今天在整理以前几个老网站的时候,发现很多低版本的wordpress主题没有这些集成功能,又不想升级wordpress版本,于是只好手动添加代码来实现自动调用文章首图为缩略图的功能。
本以为是个很简单的功能,因为网上类似的教程很多,但是发现试了几个代码都无效,甚至语法错误,大概是很多年前的代码版本了,有些不太兼容。
以下是晓兔亲测可用的一个版本:
首先在主题文件夹下找到functions.php文件,添加一段代码:
//支持外链缩略图
if ( function_exists('add_theme_support') )
add_theme_support('post-thumbnails');
function catch_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content,
$matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$random = mt_rand(1, 20);
echo get_bloginfo ( 'stylesheet_directory' );
echo '/images/random/tb'.$random.'.jpg';
}
return $first_img;
}
在random文件夹内放入文件名如tb1.jpg,tb2.jpg,tb10.jpg等随机图片。
然后新建一个thumbnail.php文件,内容为:
<div class="thumbnail">
<?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?>
<?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
<a href="<?php the_permalink() ?>" rel="nofollow" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /></a>
<?php else: ?>
<a href="<?php the_permalink() ?>" rel="nofollow" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo catch_first_image() ?>" width="140px" height="100px" alt="<?php the_title(); ?>"/></a>
<?php endif; ?>
</div>
最后在首页或文章列表页相应位置插入:
<?php include('includes/thumbnail.php'); ?>
一定要仔细注意代码内的文件夹路径和名称是否正确,方可确保正常抓取和展示缩略图。
发表于2020-11-25 at 17:22 5楼
感谢分享,谢谢站长
发表于2018-05-22 at 17:26 4楼
这个不错,学习了![[赞]](https://www.loveif.com/wp-content/themes/Blogs/images/smilies/36.gif)
发表于2018-03-23 at 22:02 地板
“最后在首页或文章列表页相应位置插入:” 我怎么不明白这个意思啊。。我是WordPress新手,你说的首页或文章页,是那个文件呀。。
@你好这个怎么弄一般是:index.php和single.php
发表于2017-09-27 at 14:38 板凳
前几天我也写过一个asp代码的获取文章第一张图片做缩略图的文章,虽然和php有些差别,不过道理都一样
发表于2017-09-26 at 10:44 沙发
学习了,博主棒棒哒