使用自定义分类隐藏循环中的子帖子

Hide children posts in loop with custom taxonomy

我创建了一个类似于类别的自定义分类法。我正在使用以下循环来显示来自该分类的帖子:

$exec_query = new WP_Query( array (
                  'post_type' => 'cars',
                  'car_type' => 'large_cars',
                  'posts_per_page' => 100,
                  'order' => 'ASC',
                  'include_children' => false
                ) );

                    //* The Loop
                    if ( $exec_query->have_posts() ) { ?>

                          <?php

                        while ( $exec_query->have_posts() ): $exec_query->the_post();

                              get_template_part( 'parts/loop', 'single-produkt' );

                        endwhile; ?>

                        <?php

                        //* Restore original Post Data
                        wp_reset_postdata();
                    }

这会显示分类 "Large cars" 中发布的所有帖子。

但是这个分类法有像 "SUV"、"Vans" 这样的子类别,并且还显示了来自这些子类别的帖子。我不想显示这个,但 include_children 似乎不起作用。

有什么想法吗?

试试这个,您必须使用 include_children 如下所示删除子分类法。

  $args = array(
             //Rest of you args go here
             'tax_query' => array(
                  array(
                      'include_children' => false
                  )
              ),
              'post_type' => 'cars',
              'car_type' => 'large_cars',
              'posts_per_page' => 100,
              'order' => 'ASC'
          );

  $query = new WP_Query( $args );

好吧,通过首先获取子类别的 ID 然后将它们从 WP_Query-array 中排除来找到解决方案:

                $term_id = get_term_by( 'slug', $term, $taxonomy)->term_id;
                $taxonomy_name = $taxonomy;
                $termchildren = get_term_children( $term_id, $taxonomy_name );
                $exclude = "";

                foreach ( $termchildren as $child ) {
                    $term2 = get_term_by( 'id', $child, $taxonomy_name );
                    $exclude = $exclude . "" . $term2->term_id . ",";
                }
                $exclude = substr($exclude, 0, -1);

                 $args = array(
                             //Rest of you args go here
                            'tax_query' =>  array (
                                array(
                                    'taxonomy' => $taxonomy, // My Custom Taxonomy
                                    'terms' => explode(',', $exclude), // My Taxonomy Term that I wanted to exclude
                                    'field' => 'id', // Whether I am passing term Slug or term ID
                                    'operator' => 'NOT IN', // Selection operator - use IN to include, NOT IN to exclude
                                ),
                            ),
                              'post_type' => $type,
                              $taxonomy  => $term,
                              'posts_per_page' => 100,
                              'order' => 'ASC',
                          );