您无需将表单的action 更改为模板文件的名称。在你的 search-custom.php 里面有:
<form action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<input type="hidden" name="s" value="<?php the_search_query(); ?>">
<input type="hidden" value="qcm" name="post_type">
<button type="submit"><span class="mr-2">Go</button>
</form>
设置此模板文件后,您可以在页面模板(您希望表单显示的页面,或者可能在侧边栏或其他内容中)中使用它:
<?php get_template_part( 'search', 'custom' ); ?>
将使用默认的wordpress搜索模板输出结果。
如果你想为结果使用不同的模板文件,你可以把它放在你的主题的functions.php文件中并更改结果页面(即search-results-custom.php):
add_action('template_include', 'search_custom_template');
function search_custom_template( $template ) {
if ( isset( $_REQUEST['search'] ) && is_search() ) {
$temp = locate_template('search-results-custom.php');
if ( ! empty($temp) ) {
$template = $temp;
}
}
return $template;
}
使用不同形式的多个搜索结果页面
如果您想在表单中设置一个值,并使用它来访问特定的结果页面:
-
打开你的主题的 search.php 文件,为安全起见复制一份,并将文件的全部内容替换为以下代码:
<?php
if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
if($type == 'qcm') {
load_template(TEMPLATEPATH . '/search-custom.php');
} elseif($type == 'another') {
load_template(TEMPLATEPATH . '/search-another.php');
}
}
?>
在此代码中,我们检查名称为 post_type 的字段设置的值。在您的问题中,您设置了qcm 的值。当该字段在提交时具有此值时,您将加载search-custom.php。如果您有其他具有其他值的表单,您只需添加一个elseif 并加载另一个搜索结果模板。
如果你想使用另一个隐藏的输入来检查值,你可以简单地创建一个:
<input type="hidden" name="my-hidden-info" value="value-to-check" />
如您所见,通过这种方式,您可以在表单中编辑一个值,并针对特定值获取不同的搜索结果页面。表单的操作没有改变,您将始终使用search.php 文件。您只需添加其他模板,您将在 if and elseif 中的此文件中加载这些模板。因此,您可以使用不同的表单获得多个搜索结果页面。