如何获取所有 [=10s in selected taxonomies custom post 类型?

How to get all posts in selected taxonimies custom post type?

我的模板中有一个名为 'faq' 的 post 类型和名为 'type' 的分类法,并创建了一些分类法术语 "Design"、"Print"、"Display"等

我试图实现的想法是只显示属于分配的分类法(类型)的 posts 而不会重复。每个 post 可以分配给多个分类法(类型)。

只要 post 只分配了一个分类法,我当前的代码就可以正常工作。一旦我分配了一个以上的分类法,它就会显示重复的 posts,如下所示:

这是我当前的代码:

                        <?php

                        $post_type = 'faq';
                        $tax = 'type';
                        $faq_types = get_field('types');

                        $filtered = array();

                        $termargs = array( 'include' => $faq_types );
                        $tax_terms = get_terms($tax, $termargs);

                        if ($tax_terms) {
                          $i = 1;
                          foreach ($tax_terms as $tax_term) {

                            $args=array(
                              'post_type' => $post_type,
                              $tax => $tax_term->slug,
                              'post_status' => 'publish',
                              'posts_per_page' => -1,
                              'caller_get_posts'=> 1
                            );

                            $my_query = null;
                            $my_query = new WP_Query($args);

                            if( $my_query->have_posts() ) {

                              while ($my_query->have_posts()) : $my_query->the_post(); ?>

                                <div class="accordion-section">
                                    <a class="accordion-section-title" href="#accordion-<?php echo $i; ?>"><i class="fa fa-chevron-right"></i> <?php the_title(); ?></a>

                                    <div id="accordion-<?php echo $i; ?>" class="accordion-section-content">
                                        <?php the_content(); ?>
                                    </div>
                                </div>

                                <?php
                              $i++;    
                              endwhile;
                            }
                            wp_reset_query();

                          }
                        }

                        ?>

如能帮助我按需要进行工作,我将不胜感激。

您当前的循环是说 "For each taxonomy term, show all posts associated with that term",因此如果有一个 post 与多个术语相关联,它当然会重复。将您的查询从 foreach 循环中取出并使用带有一组术语的单个税务查询:

$args = array(
    'post_type' => $post_type,
    'tax_query' => array(
        array(
            'taxonomy' => $tax,
            'field'    => 'slug',
            'terms'    => $term_slugs,
        ),
    ),
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'caller_get_posts'=> 1
);

编辑

顺便说一句,您需要将术语对象数组转换为术语 slug 数组才能正常工作:

$term_slugs = array();
foreach( $tax_terms as $term ) {
    $terms_slugs[] = $term->slug; 
}