WordPress已自带了搜索功能,只需在主题中添加搜索框即可启用搜索功能。具体步骤如下:
可以在主题的header.php或sidebar.php中添加搜索表单。示例代码:
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ); ?></span>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />
</label>
<button type="submit" class="search-submit"><span class="screen-reader-text"><?php echo _x( 'Search', 'submit button' ); ?></span></button>
</form>
如果您希望搜索结果有专门的页面,可以创建一个search.php文件并将其放入主题文件夹中。示例代码:
<?php get_header(); ?>
<section id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<header class="page-header">
<h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'twentyseventeen' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php if ( have_posts() ) : ?>
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/post/content', 'none' );
endif; ?>
</main><!-- #main -->
</section><!-- #primary -->
<?php get_footer(); ?>
如果您的主题使用了自定义查询,您需要启用搜索辅助功能以确保搜索结果可以与您的查询一起正常工作。示例代码:
function my_search_query( $query ) {
if ( $query->is_search() && !is_admin() ) {
$query->set( 'post_type', array( 'post', 'page' ) );
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'custom_field_1',
'value' => $query->query_vars['s'],
'compare' => 'LIKE'
),
array(
'key' => 'custom_field_2',
'value' => $query->query_vars['s'],
'compare' => 'LIKE'
)
));
}
}
add_action( 'pre_get_posts', 'my_search_query' );
以上示例仅供参考,根据主题的不同,可能需要进行相应的修改。