上一篇的 index.php 太素了。这一篇把它做成正常的文章列表:
<?php get_header(); ?>
<div class="content">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article class="post-item">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="post-meta">
<?php the_time( 'Y-m-d' ); ?> · <?php the_category( ', ' ); ?>
</div>
<p><?php the_excerpt(); ?></p>
</article>
<?php endwhile; endif; ?>
<?php the_posts_pagination( array( 'prev_text' => '上一页', 'next_text' => '下一页' ) ); ?>
</div>
<?php get_footer(); ?>
新东西只有两个:post-meta(时间 + 分类)和 the_posts_pagination(分页)。
它是 WordPress 4.1 加的,比 paginate_links 更省事:自动读主查询的页数、自动判断当前页。
the_posts_pagination( array(
'prev_text' => '上一页',
'next_text' => '下一页',
) );
只有一个条件:用于主查询。如果你用的是自定义 WP_Query,它算的是主查询的页数,会错。那种情况要用 paginate_links(卷二第 17 篇讲过)。
.pagination { margin: 30px 0; text-align: center; }
.pagination .page-numbers {
display: inline-block; padding: 6px 12px; margin: 0 3px;
border: 1px solid #ddd; text-decoration: none; color: #333;
}
.pagination .current { background: #333; color: #fff; border-color: #333; }
the_posts_pagination 输出的 HTML 带 .nav-links 和 .page-numbers,可以直接针对它写样式。
如果只有一页文章,分页函数什么都不输出。这是正常的。
如果想在“只有一页”时也显示点什么(比如“共 N 篇”),可以自己判断:
<?php
global $wp_query;
echo '共 ' . $wp_query->found_posts . ' 篇';
?>
要。首页应该有一个 h1,告诉搜索引擎“这页讲什么”。
最简做法是在列表上面加一行:
<h1 class="page-title"><?php bloginfo( 'name' ); ?></h1>
或者更 SEO 一点,写一句带关键词的描述性标题。
注意:一页只能有一个 h1。文章列表里的标题用 h2。
一句话记住:首页 = 循环 + 列表结构 + the_posts_pagination;别忘了一个 h1。
下一篇做文章页。