文章页:标题、正文、meta、相关文章

作者: admin 分类: wordpress主题制作教程 发布时间: 2026-11-06 18:45

single.php 的结构

<?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> &raquo;
    <?php the_category( ' &raquo; ' ); ?> &raquo;
    <span><?php the_title(); ?></span>
</nav>

注意用 <nav> 或 <div>,不要用 <ol> 包 <div>(卷三第 29 篇讲过的坑)。

小结

一句话记住:文章页 = 一个循环包住标题/meta/正文/标签 + 循环外评论 + 用 WP_Query 做相关文章。

下一篇做分类页和标签页。

本系列导航

相关文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Powered by 草根站长笔记 © 2015-2026 草根站长笔记 Inc.版权所有,禁止转载