<?php get_header(); ?>
<div class="content">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article>
<h1><?php the_title(); ?></h1>
<div class="post-meta">
<?php the_time( 'Y-m-d' ); ?> · <?php the_author(); ?> · <?php the_category( ', ' ); ?>
</div>
<div class="post-content">
<?php the_content(); ?>
</div>
<?php if ( has_tag() ) : ?>
<div class="post-tags"><?php the_tags( '标签:', ',', '' ); ?></div>
<?php endif; ?>
</article>
<?php endwhile; endif; ?>
<?php comments_template(); ?>
</div>
<?php get_footer(); ?>
注意:标题、meta、正文、标签,全在同一个 while 里。这是卷二反复强调的——不要为了输出某个字段单独套循环。
正文下面、评论上面,加一个相关文章:
<?php
$tags = array();
foreach ( get_the_tags() as $t ) { $tags[] = $t->term_id; }
if ( $tags ) {
$related = new WP_Query( array(
'tag__in' => $tags,
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 6,
'ignore_sticky_posts' => 1,
) );
if ( $related->have_posts() ) {
echo '<h2>相关文章</h2><ul class="related">';
while ( $related->have_posts() ) {
$related->the_post();
echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
}
echo '</ul>';
}
wp_reset_postdata();
}
?>
三个要点:
new WP_Query,不是 query_posts;post__not_in 排除自己;wp_reset_postdata()。comments_template() 放在 endwhile 之后、endif 之后,是对的。因为它内部会自己处理评论,不需要主循环的 $post。
但如果放在循环里面,可能会输出多次(虽然单篇文章只有一次循环,影响不大)。
建议要。面包屑告诉用户“你在哪”,也给搜索引擎一个层级信号。
最简写法:
<nav class="breadcrumb">
<a href="<?php echo esc_url( home_url('/') ); ?>">首页</a> »
<?php the_category( ' » ' ); ?> »
<span><?php the_title(); ?></span>
</nav>
注意用 <nav> 或 <div>,不要用 <ol> 包 <div>(卷三第 29 篇讲过的坑)。
一句话记住:文章页 = 一个循环包住标题/meta/正文/标签 + 循环外评论 + 用 WP_Query 做相关文章。
下一篇做分类页和标签页。