首页 > 解决方案 > 在 WordPress 中跨多个分类法搜索和过滤查询

问题描述

我们有一个自定义帖子类型 hr-priority,它有多个与之关联的自定义分类法。这些分类法包含多个术语,每个帖子都可以从这些分类法中分配一对多的术语。我们正在尝试设置一个过滤器,允许访问者通过这些术语的组合在多个分类中搜索/过滤结果。

例如:帖子“Sample Post”的分类“year”有“2018”一词,“org”分类有“council-member”这个词,“country”分类有“canada”这个词。“Other Sample”帖子中的“年份”为“2016”,“组织”分类为“经理”,“国家”分类为“加拿大”。“Third Post”帖子的分类“年”为“2018”,“组织”分类为“安全团队”,“国家”分类为“冰岛”。

我们希望能够按所有这些术语过滤结果,所以如果我选择只查看 year=2018 的帖子,我会得到“第三个帖子”和“示例帖子”,但如果我进一步过滤这些country=canada 我只会得到“Sample Post”(因为过滤器是 year=2018 和 country="canada")。

我正在使用搜索和过滤插件。我尝试使用archive-hr-priority.php 模板页面获取结果,但结果中根本无法识别该模板。然后我使用了自定义分类模板,例如 taxonomy-year.php,它只使用一个过滤器,所以当我按 year=2018 过滤时,返回的唯一帖子来自 2018 年,但是当我添加了第二个搜索词,例如 country="canada",它返回 country=canada 的所有结果,但包含所有年份词。

这是我的搜索和过滤简码:

echo do_shortcode( '[searchandfilter post_types="hr-priority" fields="year,country"]' );

这是我在自定义分类模板中使用的代码(我为每个分类创建了一个):

if (is_tax() || is_category() || is_tag() ){
        $qObj = get_queried_object();

        $args = array(
            'post_type'=>'hr-priority',
            'tax_query' => array( array(
                  'taxonomy' => $qObj->taxonomy,
                  'field' => 'id',
                  'terms' => $qObj->term_id
                )),
            'post_status'=>'publish',
            'posts_per_page'=>20
        );
    }
    echo($qObj->slug); //just to view the term/s being used
     $wpb_all_query = new WP_Query($args);
    if ( $wpb_all_query->have_posts() ) : ?>
        <?php
        /* Start the Loop */
        while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();

            get_template_part( 'template-parts/post/hr-priorities-post', get_post_format() );

        endwhile;

这是提交 Search&Filter 参数后返回的 URL:

https://exampleurl.org/org/council-member?country=afghanistan&post_types=hr-priority-un

如何让它按多个分类法中的多个术语过滤并仅返回与所有搜索参数匹配的结果?

标签: phpwordpresssearchpluginsfilter

解决方案


我不熟悉“搜索和过滤”,但这看起来很容易使用 base WP_Query。您可以使用以下内容跨多个分类进行搜索:

$tax_query = array(
  'relation' => 'AND'
);

// get query parameters and compose the condition
$year = $_GET['year'];
if (!empty($year)) {
  $cond = array(
    'taxonomy' => 'year',
    'field' => 'slug',
    'terms' => $year,
  ));
  $tax_query[] = $cond;
}
// Repeat for other parameters

$args = array(
  'post_type'=>'hr-priority',
  'tax_query' => $tax_query,  
  'post_status'=>'publish',
  'posts_per_page'=>20,
);

参考文档


推荐阅读