cleey
望着那一丝海线,若隐若现。落日下的海霞,数不尽的美,看不完的醉
WordPress相关文章推荐
最近想给博客做一个相关文章的推荐,文章是基于标签的推荐,可以自定义推荐篇数。可以根据自己的需要设置篇数,及其呈现方式,该文章最后就是一个相关文章推荐的实例,可以点击看看,我贴出自己的代码直接套用就行了,不一定什么都自己写。

1、首先是在function.php里面追加以下函数代码:
最好先备份一下防止错误,修改wordpress的东西得有这个习惯

// 相关文章推荐
function clin_related_article(){
?>
<div class="related_div">
<div class="related_title">推荐文章</div>
<ul class="related_posts">
<?php
$post_num = 8; // 推荐页数
$exclude_id = $post->ID; // 当前文章id
$posttags = get_the_tags(); $i = 0; // 获取标签
if ( $posttags ) {
$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
$args = array(
'post_status' => 'publish',
'tag__in' => explode(',', $tags),
'post__not_in' => explode(',', $exclude_id),
'caller_get_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num,
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<li><a rel="bookmark" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php
$exclude_id .= ',' . $post->ID; $i ++;
} wp_reset_query();
}
if ( $i < $post_num ) {
$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
$args = array(
'category__in' => explode(',', $cats),
'post__not_in' => explode(',', $exclude_id),
'caller_get_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num - $i
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<li><a rel="bookmark" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php $i++;
} wp_reset_query();
}
if ( $i == 0 ) echo '<li>没有相关文章!</li>';
?>
</ul>
</div>
<?php
}



定义一个函数为clin_related_article();接下来就在自己的页面调用,具体的位置是在单页文章的下面添加;

2、在single.php文件里面调用上面的那个函数,具体位置可以自己找找
下面加粗的地方是我添加的位置;

<div class="clin-right-block">
<div id="primary">
<div id="content" role="main">
<?php setPostViews($post->ID); ?>
<?php while ( have_posts() ) : the_post();
get_template_part( 'content-single', get_post_format() );
clin_related_article(); //相关文章
comments_template( '', true ); // 评论管理
endwhile; // end of the loop. ?>
</div>
</div>
</div>



3、最后是写写简单的css,效果就出来;
css比较简单,可根据自己的口味编写

.related_div{
margin: 10px 0;
}
.related_title{
font-size: 20px;
font-weight: bold;
margin: 10px 0;
color: gray;
}
.related_posts{
margin:5px 0px;
}
.related_posts li{
margin-left:20px;
color:#444;
list-style:circle;
font-size:14px;
line-height:26px;
padding:0 0 0 5px
}



该文章最后就是一个相关文章推荐的实例,可以点击看看,我就不截图了;效果挺棒挺棒的.
<< 上一篇 Linux服务器信息采集 js字符变量调用函数 下一篇 >>
文章标签
随意 | Created At 2014 By William Clinton | 蜀ICP备14002619号-4 |