要在WordPress中实现分类搜索功能,您需要创建一个自定义查询,以根据用户选择的分类来过滤帖子。以下是一个示例代码片段,演示如何在WordPress中实现这种功能:
<form method="get" action="<?php echo esc_url(home_url('/')); ?>">
<select name="category_filter">
<option value="">选择分类</option>
<?php
$categories = get_categories();
foreach ($categories as $category) {
echo '<option value="' . $category>term_id . '">' . $category>name . '</option>';
}
?>
</select>
<input type="submit" value="搜索">
</form>
<?php
if (isset($_GET['category_filter']) && !empty($_GET['category_filter'])) {
$category_filter = $_GET['category_filter'];
$args = array(
'post_type' => 'post', // 要搜索的文章类型
'cat' => $category_filter // 选定的分类
);
$query = new WP_Query($args);
if ($query>have_posts()) {
while ($query>have_posts()) {
$query>the_post();
// 在这里显示搜索结果,例如标题和内容
the_title();
the_content();
}
} else {
echo '未找到匹配的文章。';
}
wp_reset_postdata(); // 重置查询
}
?>
上述代码包括一个搜索表单,用户可以选择分类并提交搜索。然后,根据用户选择的分类,使用WP_Query
来查询匹配的文章,并显示它们的标题和内容。您可以将此代码添加到您的WordPress主题的模板文件中,例如search.php
或category.php
,以根据您的需求进行自定义。