Home >  > WordPress自动提取文章的第一张图片作为缩略图

WordPress自动提取文章的第一张图片作为缩略图

1

好久没有使用Wordpress了,最近因为要上英文站,所以又开始用它。

今天在使用的过程中就遇到一个问题,在网上下载的主题预览都非常不错,但都不支持自动生成缩略图的功能,需要手动设置特色图片,才会在前端显示缩略图。

在网上找了找相应的插件,也没有找到,没办法,只能手动改代码了。

1、找到缩略图代码
直接在浏览器中按F12,找到缩略图相关的代码为

2、在源代码中查找代码
打开dreamweaver,在主题的模板中搜索“post-thumbnail post-thumbnail-small”这一段代码。

3、修改代码
在找到的结果中,将原来的代码改成以下的形式(修改了第5行):

1<div class="entry-image entry-image-left">
2    <?php if(has_post_thumbnail()) { ?>
3    <a class="post-thumbnail post-thumbnail-small" href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_title(), 'class'=>'img-responsive' ) ); ?></a>
4    <?php } else { ?>
5    <a class="post-thumbnail post-thumbnail-small" href="<?php the_permalink(); ?>"><img src="<?php echo get_content_first_image(get_the_content()); ?>" />" class="img-responsive" /></a><?php } ?>       
6</div>

即在要显示缩略图的地方加入以下代码即可:

1<img src="<?php echo get_content_first_image(get_the_content()); ?>" alt="<?php the_title_attribute(); ?>" />

4.修改function
打开functions.php文件,在文件末尾加入以下代码:

1function get_content_first_image($content){
2    if ( $content === false ) $content = get_the_content();
3  
4    preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images);
5  
6    if($images){     
7        return $images[1][0];
8    }else{
9        return false;
10    }
11}

5.预览效果
打开浏览器,发现自动提取文章的第一张图片作为缩略图的功能已经实现了。

原载:蜗牛博客
网址:http://www.snailtoday.com
尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。

暧昧帖

本文暂无标签
Comment (0)
Trackback (1)

发表评论

*

*