get_search_query()
仅返回用户搜索的字符串。要显示搜索结果,您需要做更多的工作。
搜索结果将位于$wp_query
, 您可以使用循环操作它(就像任何其他页面一样)。
以下代码改编自WordPress自己的代码Twenty Twenty theme\'sindex.php
文件,并可根据您的主题进行调整search.php
文件
if ( is_search() ) {
global $wp_query;
$archive_title = sprintf(
\'%1$s %2$s\',
\'<span class="color-accent">\' . __( \'Search:\', \'twentytwenty\' ) . \'</span>\',
\'“\' . get_search_query() . \'”\'
);
if ( $wp_query->found_posts ) {
$archive_subtitle = sprintf(
/* translators: %s: Number of search results. */
_n(
\'We found %s result for your search.\',
\'We found %s results for your search.\',
$wp_query->found_posts,
\'twentytwenty\'
),
number_format_i18n( $wp_query->found_posts )
);
} else {
$archive_subtitle = __( \'We could not find any results for your search. You can give it another try through the search form below.\', \'twentytwenty\' );
}
}
if ( have_posts() ) {
$i = 0;
while ( have_posts() ) {
$i++;
if ( $i > 1 ) {
echo \'<hr class="post-separator styled-separator is-style-wide section-inner" aria-hidden="true" />\';
}
the_post();
get_template_part( \'template-parts/content\', get_post_type() );
}
}