以前实现过这个需求,就是在搜索结果后的搜索列表中显示缩略图,可是有一些小问题,就是搜索出来后,不显示分页,导致全部显示完,而且页面底部没有显示,还有的是网站首页的菜单栏浮动,一系列的问题。现在我决定改造一下上次的方法,请跟着我的思路继续往下读。
经过在网上搜索相关知识发现,其实还是挺简单的,只需要三步即可实现。
第一步:在functions.php文件里添加以下函数
//文章列表缩略图 function emtx_auto_thumbnail($pID,$thumb='thumbnail') { $blogimg = FALSE; if (has_post_thumbnail()) { $blogimg = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb); $blogimg = $blogimg[0]; } elseif ($postimages = get_children("post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0")) { foreach($postimages as $postimage) { $blogimg = wp_get_attachment_image_src($postimage->ID, $thumb); $blogimg = $blogimg[0]; } } elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) { $blogimg = $match[1]; } if($blogimg) { $blogimg = '<a href="'. get_permalink().'"><img src="'.$blogimg.'" alt="'.get_the_title().'" class="alignleft wp-post-image" /></a>'; } return $blogimg; }
第二步:在首页和文章列表页文件中添加以下代码,这个根据我们自己的需求放置,不必非得在首页和文章列表,当然一般是放文章列表文件中使用这个。
<div class="thumbnail"> <?php if(emtx_auto_thumbnail($post->ID) ) { echo emtx_auto_thumbnail($post->ID); } ?> </div>
第三步:在style.css文件中添加如下代码,当然可以放在被主题引用的其他css样式文件中。
/* 缩略图*/ .thumbnail { position: relative; float: left; margin: 6px 10px 0 0; } .thumbnail a img { width: 200px; height: 130px; }
完成这三步后,就可以实现文章列表自动调用文章中的缩略图了。
结合这篇文章,我们只需要把:
<div class="thumbnail"> <?php if(emtx_auto_thumbnail($post->ID) ) { echo emtx_auto_thumbnail($post->ID); } ?> </div>
取代:
<?php include( TEMPLATEPATH . '/thumbnail.php' ); ?> //新添加的显示缩略图的标签
这一行就行了。最后的效果就是,修复了搜索出来后不显示底部,以及解决了菜单栏浮动的问题和搜索结果太多不分页的问题。
未经允许不得转载:哈勃私语 » WordPress文章列表自动调用文章缩略图
本文共1529个字 创建时间:2017年11月3日12:15