0

I would like to have a couple of (automatically generated) taxonomy pages created by term name, term description and a listing of only the next level of subterms. (No parents and no grandchildrens)

I have set up a CPT named "Products", and a custom hierarchical taxonomy called "Structure". The taxonomy has the hierarchical terms

level1a
level1b
-level2a
-level2b
--level3a
--level4a
level1c
...

I'm trying to achieve to get taxonomy pages of /level1a/ and /level1b/level2a/ and so on.

On each of these pages there should be the term-title, the term-description and a list of direct child-terms of the current term. (No grandchildren).

In functions.php I have created the CPT with the

'rewrite' => array('slug' => 'products', 'hierarchical' => true, 'with_front' => false),

option and the custom taxonomy with the

'rewrite' => array( 'slug' => 'product', 'hierarchical' => true, 'with_front' => false),

option.

I am now struggling with the correct query in taxonomy.php to get the direct children only.

The closest i found is

<?php
$taxonomy_name = get_queried_object()->taxonomy; // Get the name of the taxonomy
$term_id = get_queried_object_id(); // Get the id of the taxonomy
$termchildren = get_term_children( $term_id, $taxonomy_name ); // Get the children of said taxonomy
// Display the children
echo '<ul>';
foreach ( $termchildren as $child ) {
  $term = get_term_by( 'id', $child, $taxonomy_name );
  echo '<li><a href="' . get_term_link( $term->name, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
?>

But this is showing all children and grandchildren

Thanks for your time.

  • hmmm I'm not familiar with get_term_children it looks like a helper method. Perhaps it would be better to skip the middleman and go direct to WP_Term_Query? – Tom J Nowell Jan 25 at 19:44
1

You have got the current term id by the following code

 $current_term_id = get_queried_object_id();

Getting all the info of chilldren of the parent, not grandchildren

$termchildren = array(
   'hierarchical' => 1,
   'show_option_none' => '',
   'hide_empty' => 0,
   'parent' => $current_term_id ,
   'taxonomy' => 'Structure'
);

$subcats = get_categories($termchildren);

// Display the children

   foreach ($subcats as $key => $value) {
        $term_link = get_term_link( $value );
        $name = $value->name;
        echo '<a href="'.$term_link.'">'.$name.'</a>';
   }

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.