现在的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'); ?>
一定要仔细注意代码内的文件夹路径和名称是否正确,方可确保正常抓取和展示缩略图。
发表评论