(本文转自博客“从良未遂”,文末附链接),由于在我的站上会出错,我修改了一个地方,给大家备用。
1、以下代码保存为related-posts.php文件:
<div class="related-posts text-center clearfix row">
<h4 class="section-title col-md-12"><span><?php esc_html_e( '相关日志', 'Lonesome' ); ?></span></h4>
<?php
$post_num = 2;
global $post;
$tmp_post = $post;
$tags = ''; $i = 0;
if ( get_the_tags( $post->ID ) ) {
foreach ( get_the_tags( $post->ID ) as $tag ) $tags .= $tag->name . ',';
$tags = strtr(rtrim($tags, ','), ' ', '-');
$myposts = get_posts('numberposts='.$post_num.'&tag='.$tags.'&exclude='.$post->ID);
foreach($myposts as $post) {
setup_postdata($post);
?>
<div class="related-post col-sm-6 col-xs-6">
<div class="related-posts-border">
<div class="entry-media">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<img src="<?php echo post_thumbnail_src(); ?>?imageView2/1/w/409/h/130/q/100" />
</a>
</div>
<div class="related-post-title">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</div>
<div class="related-post-date">
<?php the_time( get_option( 'date_format' ) ); ?>
</div>
</div>
</div>
<?php
}
}
$post = $tmp_post; setup_postdata($post);
?>
</div>
2、single.php文件里增加以下代码:
get_template_part( 'template-parts/related-posts' );
3、css代码。
.related-posts { margin-top: 50px}
.row { margin-left: -15px; margin-right: -15px;}
.text-center { text-align: center;}
.related-posts h3{ font-size: 16px; line-height: 1; position: relative; text-align: center; font-weight: 700; margin-bottom: 40px;}
.section-title { font-size: 16px; line-height: 1; position: relative; text-align: center; font-weight: 700; margin-bottom: 40px;}
.section-title:before { display: block; content: ''; border-top: 1px solid #e7e7e7; position: relative; top: 8px; z-index: 1}
.section-title span {display: inline-block; padding: 0 30px; background: #fff; position: relative; z-index: 2}
.related-post img { width: 100%}
.related-post-title { line-height: 1.2; margin: 3px 5px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden;}
.related-post-date { font-size: 12px; color: #7e7e7e}
.entry-media{margin-bottom:20px;border: 1px solid rgba(0,0,0,.05);border-radius: 8px;max-height: 160px;background: #fafafa;background-position: 50%;background-origin: border-box;background-size: cover;overflow: hidden;}
.entry-media img{width:100%;border-radius: 8px;}
4、如果有出错现象。可将上边代码里的
<img src="<?php echo post_thumbnail_src(); ?>?imageView2/1/w/409/h/130/q/100" />
修改为:
<?php the_post_thumbnail(); ?>