- A+
所属分类:WordPress
新建php文件relatepost.php,粘贴以下代码,放在主题目录。其中$post_num = 8;
表示调用相关文章数量,可修改。
//relatepost.php文件
<?php
<div class="nfrelated_posts">
<ul>
<?php
$post_num = 8;
$exclude_id = $post->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),
'ignore_sticky_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<div class="nfrelated_posts1">
<li>
<a href="<?php the_permalink(); ?> " rel="nofollow"><img src="<?php catch_image(); ?>"></a>
<div class="nfrelated_posts_tittle"><a class="nfrelated_posts_tittle" href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></div>
</li></div>
<?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),
'ignore_sticky_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num - $i
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<div class="nfrelated_posts1">
<li>
<a href="<?php the_permalink(); ?> " rel="nofollow"><img src="<?php catch_image(); ?>"></a>
<div class="nfrelated_posts_tittle"><a class="nfrelated_posts_tittle" href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></div>
</li></div>
<?php $i++;
} wp_reset_query();
}
if ( $i == 0 ) echo '<li>没有相关文章!</li>';
?>
</ul>
</div>
如果主题支持自动提取缩略图,使用特色图片时,将<img src="<?php catch_image(); ?>">
替换为<?php post_thumbnail( 90,90 ); ?>
。在single.php导航下添加以下代码。
//sigle.php添加代码
<!--相关文章-->
<div class="nfxiangguan">
<div class="nfrelated_posts">
<div class="nfxg_title"><strong>相关文章</strong></div>
<div class="nfrelated_posts">
<ul>
<?php include('relatedpost.php'); ?>
</ul></div>
</div></div>
<!--相关文章-->
对应样式表
/*相关文章*/
.nfxiangguan{
border-radius: 2px;
background: #fff;
margin: 0 0 10px 0;
padding: 10px 15px;
border: 1px solid #ccc;
overflow:hidden;
}
.nfrelated_posts {
margin-left: 5px;
width: 100%;
}
.nfrelated_posts1{
float:left;
margin-right:1%;
}
.nfrelated_posts_tittle {
margin-top: -3px;
margin-bottom: 5px;
line-height: 17px;
color: #515151 !important;
font-size: 100% !important;
width: 100%;
height: 32px;
overflow: hidden
}
.nfrelated_posts li {
float: left;
margin: 0 0 0 0
}
.nfrelated_posts ul li img {
width: 100%;
height: 100%;
background: #F4F4F4;
border: 1px solid #D8D8D8;
padding: 0px;
margin-top:2px;
}
.nfxg_title{
background:none repeat scroll 0 0 #fff;
color:#333333;
padding:0 0 0 0;
font-size:100%;
}
@media screen and (max-width: 480px) {
.nfrelated_posts1{
width:48%;
}
}
@media screen and (min-width: 481px) {
.nfrelated_posts1{
width:24%;
}

独角兽驿站
公众号