繁体   English   中英

如何在特定分类类别内执行搜索

[英]How to perform a search inside a specific taxonomy category

我的问题是:我有3种自定义分类法 ,例如'author','title'和'editor' ,每种分类法都适用于常规帖子。 假设我在“作者”字段中的“ jorge borges”中有post_1,而在“ ray bradbury”中的post_2中有。

我正在尝试使用一个包含下拉菜单的搜索表单,该菜单包含三个分类法和一个文本字段 ,因此,如果我选择“作者”并搜索“ jorge borges”,则结果将为post_1。

其他两个分类法也应像这样工作。

我找不到类似的东西,因为很多问题都涉及到创建具有所有分类法实例的下拉菜单,这不是我想要的。 我想要一个带有分类类别而不是值的下拉菜单。

好的,这是我在网站上提出并测试的内容。

请注意,这是很原始的(即没有样式),并且可能需要为其添加一些弹性,以防万一您得到一些意外的结果,但是这完全取决于您。

这是搜索表格。 我尚未添加action因为我不知道您要将表单重定向到何处。 但是,默认情况下,您将被带回到同一页面,因此您只需查询那里的帖子即可。

<form method="POST">
    <h3>Search for posts</h3>
<?php
    $taxonomies[] = get_taxonomy('author');
    $taxonomies[] = get_taxonomy('title');
    $taxonomies[] = get_taxonomy('editor');
    $options = array();

    if(!empty($taxonomies)) : foreach($taxonomies as $taxonomy) :
            if(empty($taxonomy)) : continue; endif;
            $options[] = sprintf("\t".'<option value="%1$s">%2$s</option>', $taxonomy->name, $taxonomy->labels->name);
        endforeach;
    endif;

    if(!empty($options)) :
        echo sprintf('<select name="search-taxonomy" id="search-taxonomy">'."\n".'$1%s'."\n".'</select>', join("\n", $options));
        echo '<input type="text" name="search-text" id="search-text" value=""></input>';
        echo '<input type="button" name="search" id="search" value="Search"></input>';
    endif;
?>
</form>

现在,在输出帖子之前添加此内容-

if(!empty($_POST['search-text'])) :
    $args = get_search_args();
    query_post($args);
endif;

最后,将其添加到您的function.php以便您可以获取相关的$args

function get_search_args(){

    /** First grab all of the Terms from the selected taxonomy */
    $terms = get_terms($_POST['search-taxonomy'], $args);
    $needle = $_POST['search-text'];

    /** Now get the ID of any terms that match the text search */
    if(!empty($terms)) : foreach($terms as $term) :

            if(strpos($term->name, $needle) !== false || strpos($term->slug, $needle) !== false) :
                $term_ids[] = $term->term_id;
            endif;

        endforeach;
    endif;

    /** Construct the args to use for quering the posts */
    $args = array(
        'order'         => ASC,
        'orderby'       => 'name',
        'post_status'   => 'publish',
        'post_type'     => 'post',
        'tax_query'     => array(
            array(
                'taxonomy'  => $_POST['search-taxonomy'],
                'field'     => 'term_id',
                'terms'     => $term_ids,
                'operator'  => 'IN'
            )
        )
    );

    return $args();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM