首先创建一个函数以显示搜索表单
function display_custom_search_form($atts){
$return = \'<form role="search" method="get" id="searchform" action="\'.home_url( \'/\' ).\'">
<div><label class="screen-reader-text" for="s">Search for:</label>
\'.wp_dropdown_categories(array(\'name\' =>\'taxTerm\', \'taxonomy\' => \'TAXONOMY_NAME\').\'
<!-- this is the magic field you will need to change in order for this to work with each post types--->
<input type="hidden" name="post_type" value="post" />
<input type="submit" id="searchsubmit" value="Search" />
<input type="hidden" name="custom_search" value="1">
</div>
</form>\';
if ($echo){
echo $return;
}else{
return $return;
}
}
将此函数挂接为一个快捷码,以便您可以在任何地方使用它(帖子/页面/小部件)
add_shortcode(\'my_c_s\',\'display_custom_search_form\');
add_filter(\'widget_text\', \'do_shortcode\');
然后检查表单是否已提交,如果已提交,则可以根据以下内容筛选帖子:
//was the form submitted
if (isset($_GET[\'custom_search\']) && $_GET[\'custom_search\'] == 1){
add_filter(\'pre_get_posts\',\'Custom_Search_Filter\');
}
//function to actually filter the posts based on the taxonomy term and post type
function Custom_Search_Filter($query) {
//only do this on search
if (is_search()){
//first check for the first type if not set then its the default post.
$post_type = $_GET[\'post_type\'];
if (!$post_type) {
$post_type = \'post\';
}
$query->set(\'post_type\', $post_type);
//then check for the taxonomy term
if (isset($_GET[\'taxTerm\'])){
$query->set(\'TAXONOMY_NAME\', $_GET[\'taxTerm\']);
}
}
return $query;
}
将所有代码复制到主题的函数中。phpand将TAXONOMY\\u NAME更改为您的实际自定义分类名称(它有两次)。
打开您的小部件面板,添加一个简单的文本小部件[my_c_s]
内部并保存。