现在首页的标题是一行死字,点不动。要看到文章页,得先能点进去。
把循环里那句 the_title( '<h2>', '</h2>' ) 换成:
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
the_permalink() 输出这一篇的地址。
标题现在是链接了,点进去——页面没变。还是那张列表。
不是报错,也没跳回首页,就是原样不动。你会以为自己点错了。
WordPress 决定「用哪个文件显示这个页面」,有一套固定顺序,叫模板层级。访问一篇文章时,它按这个顺序挨个找:
single-post-文章别名.phpsingle-post.phpsingle.phpsingular.phpindex.php找到哪个用哪个。你现在只有 index.php,前四个都不存在,所以它一路找到最后——用「列文章」的模板去显示了一篇文章。
于是你看到的是全站列表,不是你要看的那一篇。
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php bloginfo( 'name' ); ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php while ( have_posts() ) : the_post(); ?>
<article>
<h1><?php the_title(); ?></h1>
<p><?php the_date(); ?></p>
<?php the_content(); ?>
</article>
<?php endwhile; ?>
<?php wp_footer(); ?>
</body>
</html>
注意:这一篇我把整个骨架又写了一遍,跟 index.php 里那份几乎一样。先忍着这份重复,下一篇专门收拾它。
这里没有 if ( have_posts() ) 的判断,直接 while——因为进了 single.php,就说明确实有一篇文章,不用再问「有没有」。
还有一个变化:列表页用 the_excerpt()(摘要),这里用 the_content()(全文)。这就是为什么点进去以后,内容一下子变长了。
| 要做的事 | 能不能用 |
|---|---|
| 首页列出文章 | 能 |
| 点进去看单篇 | 能 |
| 全站统一的头和尾 | 还没有,两个文件各写一份 |
下一篇:把重复的那两份头尾抽出来。
本系列:迭代式建主题 · 目录(72 篇) | 上一篇 (02) | 下一篇 (04)