1

I am using $custom_terms = get_term_children( $term_id, $taxonomy_name ); to display child terms for the current taxonomy term. What I would like to do is exclude the 4th level terms as I don't want to display them and nothing that I have tried so far like 'hide_empty' and 'parent' haven't worked for me.

I found this question that is similar to what I am trying to do: https://stackoverflow.com/questions/28079153/wp-query-exclude-all-terms-of-a-custom-taxonomy

I do not want to explicitly declare which terms to exclude because there are so many and the client may add more. I need this to be dynamic and not display the 4th level terms for the current taxonomy.

My taxonomies are 4 levels deep:

Level 1 > Level 2 > Level 3 > Level 4

Here is my code so far:

$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
        ),
     ),
  );
}
0

If you have only 4 level, and each third level term has children, the we can determine the fourth level term if have children:

$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,
            ],
        ],
    ];
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.