我正在重建此网站-http://www.mediwales.com/news 在WP平台上。我正在努力寻找灰色框中的搜索区域。
我正在删除区域和日期,所以我们不必担心这些,但如何按关键字和部门设置搜索?
我已经创建了一个称为“news”的自定义分类法,它将代表各个部门。据我所知,正常的搜索只是在整个网站上搜索一个关键字。如何设置搜索以搜索关键字,但如果选择了某个扇区,则仅搜索该扇区内的关键字?然后显示结果。
更新时间:
<?php $args = array(
\'show_option_all\' => \'\',
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'show_last_update\' => 0,
\'style\' => \'\',
\'show_count\' => 0,
\'hide_empty\' => 1,
\'use_desc_for_title\' => 1,
\'child_of\' => 0,
\'feed\' => \'\',
\'feed_type\' => \'\',
\'feed_image\' => \'\',
\'exclude\' => \'\',
\'exclude_tree\' => \'\',
\'include\' => \'\',
\'hierarchical\' => true,
\'title_li\' => \'\',
\'show_option_none\' => __(\'No categories\'),
\'number\' => NULL,
\'echo\' => 1,
\'depth\' => 0,
\'current_category\' => 0,
\'pad_counts\' => 0,
\'taxonomy\' => \'news\',
\'walker\' => \'Walker_Category\' );
?>
<?php echo wp_list_categories($args); ?>
<?php
function Search_with_in_a_tax( &$query ) {
if ( is_search() && isset($_GET[\'sector_array\'])) {
$tax_query = array(
array(
\'taxonomy\' => \'news\',
\'terms\' => $_GET[\'sector_array\'],
\'field\' => \'term_id\',
)
);
//turn it into a WP_Tax_Query object
$tax_query = new WP_Tax_Query($tax_query);
$query->set("tax_query", $tax_query);
}
}
add_action(\'pre_get_posts\', \'Search_with_in_a_tax\', 1);
?>
<form method="get" id="searchform" action="<?php bloginfo(\'home\'); ?>/">
<div><input type="text" size="18" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" class="btn" />
</div>
</form>
这就是我目前所拥有的。它似乎在搜索关键词并挑选新闻。但我无法选择扇区(如顶部的链接)?我如何将两者联系起来?然后,搜索将在该部门(分类法)中搜索关键字。
最合适的回答,由SO网友:Bainternet 整理而成
您可以使用pre_get_posts
hoot可仅将搜索查询筛选到选定的扇区,类似于以下内容:
function Search_with_in_a_tax( &$query ) {
if ( is_search() && isset($_GET[\'sector_array\'])) {
$tax_query = array(
array(
\'taxonomy\' => \'news\',
\'terms\' => $_GET[\'sector_array\'],
\'field\' => \'term_id\',
)
);
//turn it into a WP_Tax_Query object
$tax_query = new WP_Tax_Query($tax_query);
$query->set("tax_query", $tax_query);
}
}
add_action(\'pre_get_posts\', \'Search_with_in_a_tax\', 1);
Update:将上面的代码放在函数处。主题的php文件,然后需要将类别(扇区)输出为搜索表单中的表单字段,因此请尝试以下操作:
<form method="get" id="searchform" action="<?php bloginfo(\'home\'); ?>/">
<div>
<label for="s">Keyword</label>
<input type="text" size="18" value="" name="s" id="s" />
</div>
<div>
<label for="sector_array">Sectors</label>
<?php
$categories=get_categories(array(\'orderby\' => \'name\',\'order\' => \'ASC\'));
foreach ($categories as $category) {
echo \'<input type="checkbox" name="sector_array[]" value="\'.$category->cat_ID.\'">\'.$category->cat_name;
}
?>
</div>
<div>
<input type="submit" id="searchsubmit" value="Search" class="btn" />
</div>
</form>