我发现这段代码非常适合我正在编写的代码,但需要稍作修改。我需要的是只显示父级的子类别。
如何更改get_categories()
只获取我需要的特定类别?因为这样做将显示所有可用类别。
function ba_SearchFilter($query) {
if (!$query->is_search) {
return $query;
}
if (isset($_POST[\'cat\'])){
$query->set(\'category__and\', $_POST[\'cat\']);
}
if (isset($_POST[\'tags\'])){
$query->set(\'tag__and\', $_POST[\'tags\']);
}
return $query;
}
//hook filters to search
add_filter(\'pre_get_posts\',\'ba_SearchFilter\');
function ba_search_with_filters(){
$out = \'<form role="search" method="get" id="searchform" action="\'. home_url( \'/\' ).\'">
<div><label class="screen-reader-text" for="s">Search for:</label>
<input type="text" value="" name="s" id="s" /><br />\';
$categories= get_categories();
foreach ($categories as $category) {
$option = \'\';
$option .= \'<input type="checkbox" name="cat[]" id="cat[]" value="\'.$category->term_id.\'"> \';
$option .= $category->cat_name .\'<br />\';
$out.= $option;
}
$tags= get_categories();
foreach ($tags as $tag) {
$option = \'\';
$option .= \'<input type="checkbox" name="tags[]" id="tags[]" value="\'.$tag->term_id.\'"> \';
$option .= $tag->cat_name .\'<br />\';
$out.= $option;
}
$out .=\'<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>\';
return $out;
}
add_shortcode(\'search_with_filter\',\'ba_search_with_filters\');
SO网友:MIke
为添加了参数$categories
输入父级的ID以显示所有子类别。
function ba_SearchFilter($query) {
if (!$query->is_search) {
return $query;
}
if (isset($_POST[\'cat\'])){
$query->set(\'category__and\', $_POST[\'cat\']);
}
if (isset($_POST[\'tags\'])){
$query->set(\'tag__and\', $_POST[\'tags\']);
}
return $query;
}
//hook filters to search
add_filter(\'pre_get_posts\',\'ba_SearchFilter\');
function ba_search_with_filters(){
$out = \'<form role="search" method="get" id="searchform" action="\'. home_url( \'/\' ).\'">
<div><label class="screen-reader-text" for="s">Search for:</label>
<input type="text" value="" name="s" id="s" /><br />\';
$args = array ( \'child_of\' => 1 );
$categories= get_categories( $args );
foreach ($categories as $category) {
$option = \'\';
$option .= \'<input type="checkbox" name="cat[]" id="cat[]" value="\'.$category->term_id.\'"> \';
$option .= $category->cat_name .\'<br />\';
$out.= $option;
}
$out .=\'<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>\';
return $out;
}
add_shortcode(\'search_with_filter\',\'ba_search_with_filters\');
SO网友:AddWeb Solution Pvt Ltd
替换以下两行代码:
$categories= get_categories();
到$categories= get_categories(array(\'hide_empty\' => 0 ));
和
$tags= get_categories();
到$tags= get_categories(array(\'hide_empty\' => 0 ));
我添加array(\'hide_empty\' => 0 )
参数跳过空列表。希望这对你有帮助!