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

将以下代码插入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;
}
您可能也喜欢这些文章:
- 2011/03/28 — 纯代码实现Thesis主题分页导航功能 (3)
- 2012/03/25 — 【Infographic】解剖WordPress主题的结构、功能 (3)
- 2011/06/22 — 纯代码实现WordPress相关文章功能 (13)
- 2011/06/17 — 纯代码实现外链自动添加小图标 (7)
- 2011/03/03 — 如何在Thesis主题中启用WP-PageNavi插件 (1)
- 2011/03/03 — Root Android 2.1~3.0终极教程(索爱E15i为例) (19)
- 2011/02/22 — WordPress优化之开启Gzip压缩 (8)
- 2011/02/10 — Wordpress技巧—从导航菜单移除特定页面 (6)

{ 1 Comment }
I’ve been surfing on-line greater than three hours today, but I by no means discovered any fascinating article like yours. Itˇs pretty worth enough for me. In my view, if all website owners and bloggers made good content material as you did, the net might be a lot more useful than ever before.