首页 问答 正文

如何使用WordPress站内搜索功能?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 138 次

WordPress站内搜索功能可以通过在模板中添加搜索表单来实现。

例如,在头部菜单添加一个搜索框,可以使用以下代码:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <input type="text" value="" name="s" id="s" placeholder="Search...">
    <button type="submit" id="searchsubmit"><i class="fa fa-search"></i></button>
</form> 

该代码将在头部菜单中创建一个搜索框,并使用 home_url() 函数指定搜索结果页面的链接。通过 name="s" 指定搜索关键字的参数名称。

在搜索结果页面,WordPress会自动为我们提供搜索结果,无需再添加额外的代码。

需要注意的是,如果使用了自定义的 post type,需要在 pre_get_posts 钩子函数中加入一些代码,来让 WordPress 在搜索时也能检索到自定义 post type。例如:

function search_custom_post_type( $query ) {
    if ( $query->is_search() && $query->is_main_query() ) {
        $query->set( 'post_type', array('post', 'page', 'my_custom_post_type') );
    }
}
add_action( 'pre_get_posts', 'search_custom_post_type' ); 

该代码将在搜索时检索自定义 post type my_custom_post_type。需要注意的是,pre_get_posts 钩子函数必须写在 functions.php 文件中。

大家谈论
    我的见解