相关文章的调用方法很多,可以直接上插件,也可以从其他博主那里找来代码修改之后贴上。我目前用的也是自己修改的代码,主要内容来自 willin 的相关文章,经过了 zww 大叔修正。不知道其中过程是怎样,对于懒得深究代码运行过程的我来说,改了改输出,看一下能用就行了。最近有几位朋友说希望分享出来,就拿出来共享一下了。
php部分(写在single.php或者其他需要的地方)
ID; // 單獨使用要開此行 //zww: edit
$posttags = get_the_tags(); $i = 0;
if ( $posttags ) {
$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ','; //zww: edit
$args = array(
'post_status' => 'publish',
'tag__in' => explode(',', $tags), // 只選 tags 的文章. //zww: edit
'post__not_in' => explode(',', $exclude_id), // 排除已出現過的文章.
'ignore_sticky_posts' => 1,
'orderby' => 'comment_date', // 依評論日期排序.
'posts_per_page' => $post_num
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
post_content; //axiu: 获取文章第一个图片
$soImages = ']*\ />';
preg_match_all( $soImages, $soContent, $thePics );
$allPics = count($thePics[0]);
if( $allPics > 0 ){
echo '* [';
echo $thePics[0][0];
echo '](';
echo the_permalink();
echo ')'.the_title().'
';
}
else {
echo '* [.'/images/default.jpg)';
echo '](';
echo the_permalink();
echo ')'.the_title().'
';
}?>
ID; $i ++;
} wp_reset_query();
}
if ( $i < $post_num ) { // 當 tags 文章數量不足, 再取 category 補足.
$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
$args = array(
'category__in' => explode(',', $cats), // 只選 category 的文章.
'post__not_in' => explode(',', $exclude_id),
'ignore_sticky_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num - $i
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
post_content; //axiu: 获取文章第一个图片
$soImages = ']*\ />';
preg_match_all( $soImages, $soContent, $thePics );
$allPics = count($thePics[0]);
if( $allPics > 0 ){
echo '* [';
echo $thePics[0][0];
echo '](';
echo the_permalink();
echo ').'.the_title().'
';
}
else {
echo '* [.'/images/default.jpg)';
echo '](';
echo the_permalink();
echo ')'.the_title().'
';
}?>
没有相关文章!';
?>
写完就剩下css定义了(参照无觅插件的显示效果制作),奉上我自己目前(截至本文发稿未知)用的
.relatedposts{
width:600px;
_width:280px;
margin:10px 0 5px 35px;
overflow:hidden;
padding:0
}
.relatedposts a{
line-height:13px;
font: 12px/15px arial;
text-decoration:none;
display:block;
overflow:hidden
}
.relatedposts li{
float:left;
width:98px;
height:130px;
list-style: none;
padding:5px 5px 9px 5px;
overflow: hidden;
background:#fefefe;
border-right:1px solid #dfdfdf
}
.relatedposts li:hover{
background:#f3f3f3
}
.relatedposts li:hover a{
color:#333
}
.relatedposts img{
height: 96px;
border:0;
padding:0
}
PS:关于默认图片(我用的是麻美妹子的图):新建一个default.jpg,然后放在主题的images文件夹下就可以了。