searchform.php 和 search.php,只差三个字母,管的事完全不同:
| 文件 | 管什么 |
|---|---|
searchform.php |
搜索输入框长什么样 |
search.php |
搜索结果页长什么样 |
很多人以为有了 searchform.php 就有搜索结果页了——其实搜索结果页还是用 index.php 兜着。
模板里调一行:
<?php get_search_form(); ?>
它做的事:
searchform.php;所以你想自定义搜索框样式,就建一个 searchform.php。
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
<div class="form-group">
<label class="screen-reader-text" for="s"></label>
<input type="text" class="form-control" value="<?php the_search_query(); ?>" name="s" id="s" />
</div>
<button type="submit" class="btn btn-default" id="searchsubmit">搜索内容</button>
</form>
几个要点:
action 是首页地址(搜索是提交到首页,带 ?s=关键词);method="get"(搜索必须用 get,不能 post);name="s"(必须是 s,WordPress 认这个);the_search_query() 把当前搜索词回填进去,搜完还能看到自己搜了什么。如果写成 name="keyword",WordPress 收不到,搜出来永远是空。必须 name="s"。
caogenbj 的 <label class="screen-reader-text" for="s"></label> 是空的。这个 label 本来是给屏幕阅读器用的(无障碍),空着不算大错,但更好的做法是写上文字:
<label class="screen-reader-text" for="s">搜索</label>
screen-reader-text 这个 class 会让文字在视觉上隐藏,但读屏软件能读到。
回到前面讲过的模板层级:搜索页走 search.php → index.php。
caogenbj 没有 search.php,所以搜索结果页用的是 index.php——标题还是首页的标题,列表还是首页的列表,用户根本看不出自己在“搜索”。
想改的话,建一个 search.php,开头写清楚“搜索「xxx」的结果”。
一句话记住:searchform.php 管输入框(name 必须是 s),search.php 管结果页;两者缺一不可。
下一篇讲评论区。