如何排除分类中最低级别的术语?

时间:2017-08-17 作者:Neelam Khan

我正在使用$custom_terms = get_term_children( $term_id, $taxonomy_name ); 显示当前分类术语的子术语。我想做的是排除第四级术语,因为我不想显示它们,也不想显示我迄今为止尝试过的任何内容\'hide_empty\'\'parent\' 没有为我工作过。

我发现这个问题与我想做的相似:https://stackoverflow.com/questions/28079153/wp-query-exclude-all-terms-of-a-custom-taxonomy

我不想明确声明要排除哪些术语,因为它们太多了,客户可能会添加更多。我需要它是动态的,并且不显示当前分类法的第四级术语。

我的分类有4个层次:

级别1>级别2>级别3>级别4

以下是我目前的代码:

$term_id = get_queried_object()->term_id;
$taxonomy_name = \'product_range\';
$custom_terms = get_term_children( $term_id, $taxonomy_name );

foreach($custom_terms as $custom_term) {

  $term = get_term_by( \'id\', $custom_term, $taxonomy_name );
  wp_reset_query();
  $args = array(
    \'post_type\' => \'product\',
    \'posts_per_page\' => 1,
    \'tax_query\' => array(
      array(
        \'taxonomy\' => \'product_range\',
        \'field\' => \'slug\',
        \'terms\' => $term->slug,
        \'parent\' => 0
        ),
     ),
  );
}

1 个回复
SO网友:Amos Lee

如果您只有4个级别,并且每个第三级别术语都有子级,那么如果有子级,我们可以确定第四级别术语:

$term_id       = get_queried_object()->term_id;
$taxonomy_name = \'product_range\';
$custom_terms  = get_term_children( $term_id, $taxonomy_name );

foreach ( $custom_terms as $custom_term ) {

    $term          = get_term_by( \'id\', $custom_term, $taxonomy_name );
    $terms_chilren = get_term_children( $term_id, $taxonomy_name );

    wp_reset_query();

    // if we can not get a term`s children, we can confirm the term is the fourth level term.
    if ( ! empty( $terms_chilren ) && ! is_wp_error( $terms_chilren ) ) {
       $args = [
        \'post_type\'      => \'product\',
        \'posts_per_page\' => 1,
        \'tax_query\'      => [
            [
                \'taxonomy\' => \'product_range\',
                \'field\'    => \'slug\',
                \'terms\'    => $term->slug,
                \'parent\'   => 0,
            ],
        ],
    ];
  }
}

结束

相关推荐

How to get terms for taxonomy

如何获取分类法customcategorie的所有术语我试图在分类法中保留代码。php<?php /* Template Name:Taxoo */ get_header(); ?> <?php $term = get_term_by( \'slug\', get_query_var( \'term\' ), get_query_v