如何搜索类别和/或标签?

时间:2011-05-15 作者:Mr B

我的博客上有一个搜索功能。如果我输入一个值,在搜索框中说“水果”,但它在任何帖子中都不匹配,但它是博客中某个类别的名称,那么我希望显示属于该类别的帖子。

是否可以修改搜索功能,使其涵盖博客中所有类别和可能的标签的搜索?

非常感谢。

2 个回复
SO网友:kaiser
// Above the loop on your search result template:
if ( is_search() ) // Are we on a search result page?
{
    global $wp_query, $query_string;
    // now modify/filter the query (result)
    query_posts( $query_string . \'cat=1&tag=apples+apples\' );
}
SO网友:Husky

这里有一个函数,它将搜索与给定字符串匹配的任何类别(或其他分类法),然后返回该类别中包含的所有帖子。

function searchTermPosts(String $query) {
    // First get the categories / taxonomies that have a \'name like\' the query
    $terms = get_terms([ "name__like" => $query ]);

    // Now convert to a taxonomy query we can use in WP_Query
    $tax_query = array_map(function ($term) {
        return [
            "taxonomy" => $term->taxonomy,
            "terms" => $term->term_taxonomy_id
        ];
    }, $terms);

    // Add an "OR" clause to find posts in all categories
    $tax_query["relation"] = "OR";

    // Now do the query
    $results = new \\WP_Query([
        "tax_query" => $tax_query
    ]);

    // Return both results and the terms, as well as term names
    return [
        "results" => $results,
        "terms" => $terms,
        "term_names" => array_map(fn ($t) => $t->name, $terms)
    ];
}
然后像这样使用:

$query = searchTermPosts("fruits");
$count = $query[\'results\']->found_posts;
$cats = implode(",", $query[\'term_names\']);

echo "Found $count results in these categories: $cats";
echo "<ul>";

while ($query[\'results\']->have_posts()) {
    $query[\'results\']->the_post();
    echo \'<li><a href="\' . get_the_permalink() . \'">\';
    the_title();
    echo \'</a></li>\';
}

echo "</ul>";

结束