当我们在使用WordPress中使用搜索功能时,就会用到search.php模板,它用于显示搜索结果页面。
搜索框的两种添加方式
第一种方式:外观 >> 工具
为了让网站拥有搜索框,可以在 WordPress 后台,进入外观 >> 工具,并确保我们启用了搜索小工具:
You must be logged in to view the hidden contents.
第二种方式:get_search_form()模板标签
可以使用函数:get_search_form()。它同样会为我们显示搜索框。它的功能实际上就是:通过调用searchform.php来显示搜索框。
所以,如果您的网站主题中有一个自定义的searchform.php文件,WordPress将使用这个自定义的php文件来显示搜索框。
但是,如果您没有自定义的 searchform.php ,WordPress将显示默认的搜索框。
search.php模板
让我们来看看网站前台的搜索框的样子。
进入到Blog页面,然后点击搜索单词Hello:
search.php wordpress02 - WordPress模板层次16:搜索模板search.php
搜索结果页面如下图:
可以看到:
search.php wordpress05 - WordPress模板层次16:搜索模板search.php
在模板结构图中,可以看到search.php文件,这个文件决定咱们的搜索页面长什么样子:
search.php wordpress06 - WordPress模板层次16:搜索模板search.php
来到示例主题中的search.php模板。可以看到这些代码复合我们的预期:
当找不到搜索结果时,执行else中的语句,我们需要考虑在网站中找不到搜索词的情况,也就是说,如果用户在网站上搜索一些网站上没有的东西,比如hehe,我们应该给出提示信息,并且再给出一个搜索框,方便用户重新搜索:
search.php wordpress07 - WordPress模板层次16:搜索模板search.php
这在WordPress中是一种常见做法,所有的搜索功能也都应该这么做。
其实,大家还需要考虑的是:网站是否需要搜索框,如果内容很多,那么搜索框就很有必要,相反,如果网站只是几个静态页面,添加一个搜索框就显得有些多余。