当我们在使用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:





WordPress模板层次16:搜索模板search.php_自定义



​search.php wordpress02 - WordPress模板层次16:搜索模板search.php​



搜索结果页面如下图:

可以看到:




WordPress模板层次16:搜索模板search.php_自定义_02



​search.php wordpress05 - WordPress模板层次16:搜索模板search.php​



在​​模板结构图​​中,可以看到search.php文件,这个文件决定咱们的搜索页面长什么样子:




WordPress模板层次16:搜索模板search.php_php_03



​search.php wordpress06 - WordPress模板层次16:搜索模板search.php​



来到示例主题中的search.php模板。可以看到这些代码复合我们的预期:

<?php get_header(); ?>

<div class="container" role="main">

<div class="row">

<div class="col-md-12">

<div class="page-header">
<h1><?php wp_title( '' ); ?></h1>/***wp_title()输出了搜索结果的标题***/
</div>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>/***循环***/

<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>/***文章标题***/

<p class="meta">/***文章相关的信息(作者、时间、评论)***/
By <?php the_author_posts_link(); ?>
on <?php echo the_time('l, F jS, Y'); ?>
<a href="<?php comments_link(); ?>"><?php comments_number(); ?></a>
</p>

<?php the_content(); ?>/***文章的内容***/

<?php endwhile; else: ?>/***找不到搜索结果时,执行else中的语句***/

<p>No results :(</p>

<p><?php get_search_form(); ?></p>/***调用搜索框***/

<?php endif; ?>

</div>

</div>

</div>

<?php get_footer(); ?>

当找不到搜索结果时,执行else中的语句,我们需要考虑在网站中找不到搜索词的情况,也就是说,如果用户在网站上搜索一些网站上没有的东西,比如hehe,我们应该给出提示信息,并且再给出一个搜索框,方便用户重新搜索:




WordPress模板层次16:搜索模板search.php_自定义_04



​search.php wordpress07 - WordPress模板层次16:搜索模板search.php​



这在WordPress中是一种常见做法,所有的搜索功能也都应该这么做。

其实,大家还需要考虑的是:网站是否需要搜索框,如果内容很多,那么搜索框就很有必要,相反,如果网站只是几个静态页面,添加一个搜索框就显得有些多余。