wordpress中提取文章内第一张图片作为缩略图

作者:matrix 被围观: 1,901 次 发布时间:2013-09-04 分类:Wordpress 兼容并蓄 | 无评论 »

这是一个创建于 4221 天前的主题,其中的信息可能已经有所发展或是发生改变。

网上有很多类似的代码,大多都来自知更鸟的HotNews。略有不同,这里还是记录一下。

一.模板函数中添加:

<?php //取文章内first_image  
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(emptyempty($first_img)){
$random = mt_rand(1,10);
echo get_bloginfo ( 'stylesheet_directory');
echo '/images/random/'.$random.'.jpg';//若没有则输出/images/random/内图片
}
return $first_img;
}

?>

二.主题目录内新建includes文件夹,thumbnail.php丢入:

<?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?><div class="thumbnail_t">  
<?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>"/></a></div>
<?php else: ?>

<!-- 截图 -->
<div class="thumbnail">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
<?php if (has_post_thumbnail()) { the_post_thumbnail('full'); }
else { ?>
<img src="<?php echo catch_first_image() ?>" alt="<?php the_title(); ?>"/>
<?php } ?>
</a>
<?php endif; ?>
</div>

三.在需要显示缩略图的地方(我这是首页列表index.php中)添加:

<div id=""><?php include('includes/thumbnail.php'); ?></div>  

说明:thumbnail.php路径要与上一步设置的路径对应一致。

这里也可以省略includes/thumbnail.php的设置,直接把第二步的代码放在在需要显示缩略图的地方。

要求不高的之后也就没啥事情了。

有了个缩略图也需要设置个样式:

/*缩略图*/  
.thumbnail {
margin-right: 10px;
width:140px;
height:100px;
overflow:hidden;
border:3px solid #e7e7e7;
POSITION:relative;
float: left;
}
.thumbnail_t {
margin-right: 10px;
width:140px;
height:100px;
overflow:hidden;
border:3px solid #e7e7e7;
POSITION:relative;
float: left;
}

说明:这里的thumbnail、thumbnail_t   class都是呵上面对应的。

效果:

添加css后的效果

 

设置了缩略图也少不了裁剪些内容,以免太杂了,整齐一些。

<?php echo mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,420,'......'); ?>  
<a title="<?php the_title(); ?>" href="<?php the_permalink() ?>">阅读全文 » </a>

说明:1行为自动截取文章的前420个字符,以“......”结尾

2行为显示阅读全文的链接,这个需要替换掉诸如此类显示read more 的代码:

<?php the_content(__('阅读剩余部分 »')); ?>  

这样的话首页index上基本完成,TAG、category页面就以此类推

效果:

NGRO 主题中的效果

参考:

http://tieba.baidu.com/p/2322869684

http://zmingcx.com/display-a-different-random-thumbnails.html

其他文章:
本文固定链接:https://www.hhtjim.com/wordpress-to-extract-the-articles-within-the-first-picture-as-thumbnails.html
matrix
本文章由 matrix 于2013年09月04日发布在Wordpress, 兼容并蓄分类下,目前没有通告,你可以至底部留下评论。
转载请注明:wordpress中提取文章内第一张图片作为缩略图-HHTjim'S 部落格
关键字:, , ,

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!
 
载入中...