纯代码实现Thesis主题相关文章功能

相关文章插件一大堆,其中尤以【我爱水煮鱼的WordPress Related Posts】和无觅网的【无觅相关文章插件】最为出名。但是他们终究是插件,必定会影响网页加载速度,笔者今天成功实现了Thesis主题纯代码实现相关文章,而且效果和无觅相关文章插件类似,带有文章缩略图。下面是效果图:

custom related posts

将以下代码插入custom_functions.php文件中:

add_theme_support( 'post-thumbnails' );
add_image_size( 'related-posts', 100, 100, true ); 

function related_posts() {
if ( is_single() ) {
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'caller_get_posts'=>1,
'orderby'=>'rand'
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts" class="clear"><h3>Read them too</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<li>
<a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
<?php the_post_thumbnail( 'related-posts' ); ?>
</a>
<div class="related_content">
<a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</div>
</li>
<? }
echo '</ul></div>';
} }
$post = $orig_post;
wp_reset_query(); ?>

<?php thesis_post_tags(); ?>
<?php } else { } }

add_action('thesis_hook_after_post','related_posts');

上面这段代码有两个作用,一个是激活WordPress文章缩略图(thumbnails)功能,作为相关文章显示的缩略图;另一个是在文章后面插入相关文章。下面是一段笔者博客使用的CSS代码,仅供参考(可以根据自己的博客修改):

.custom #related_posts ul
{
	overflow:hidden;
	margin:0;
	padding:5px 0;
}

.custom #related_posts li
{
	float:left;
	list-style:none;
	margin:0 0 0 20px;
}

.custom #related_posts li:first-child
{
	margin-left:3px;
	padding-left:8px;
}

.custom #related_posts li a
{
	border-bottom:medium none;
	display:block;
	font-size:13px;
	line-height:16px;
	text-align:left;
	text-decoration:none;
	width:80px;
}

.custom #related_posts li a:hover
{
	text-decoration:underline;
}

.custom #related_posts li a img
{
	background:none repeat scroll 0 0 #EEE;
	border:1px solid #E1E1E0;
	height:66px;
	padding:4px;
}

.custom #related_posts li a img:hover
{
	background:#DDD;
	border:1px solid #CCC;
}

.custom #related_posts
{
	height:210px;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>