0

I am trying to list only the children of a chosen parent category. The following code lists all children. I would like to just be able to change the id or something of the parent to only list children from that selected parent.

<?php

$taxonomy_name = 'download_category';
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;

$termchildren = get_the_terms( $post->ID, $taxonomy_name, array( 'parent' => $term_id, 'hide_empty' => false ) );

echo '<ul>';
   foreach ( $termchildren as $child ) {
   echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $child->name . '</a></li>';
   }
echo '</ul>';

?>   

Please if someone can help. Thanks

1 Answer 1

0

Based on our comment discussion, you're using the code in a sidebar widget (that accepts php code) on a single post page.

It ended up being much more complex than expected. This should work though.

<?php
$taxonomy = 'download_category';
$terms    = wp_get_object_terms( get_the_ID(), $taxonomy );
$parents  = array();

// Loop through all album categories.
foreach ( $terms as $term ) {

  // Get the parent terms of each category (if any).
  if ( 0 < $term->parent ) {
    $ancestors = get_ancestors( $term->term_id, $taxonomy );

    // Get the parent term object.
    $parent = get_term_by( 'id', $ancestors[0], $taxonomy );
    $parents[$parent->name] = $parent->term_id;

    // Put children in array to use below.
    $children[] = $term;
  }
}

// Exit if no parents found.
if ( empty( $parents ) ) {
  return _e( 'No parent categories found.' );
}

// Loop through all parents and output their children.
foreach ( $parents as $parent_name => $parent_id ) {

  echo '<h3>' . $parent_name . '</h3>';
  echo '<ul>';
  foreach ( $children as $child ) {
    if ( $child->parent == $parent_id ) {
      echo '<li><a href="' . get_term_link( $child, $taxonomy ) . '">' . $child->name . '</a></li>';
    }
  }
  echo '</ul>';
}
?>
1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Howdy_McGee
    Oct 2, 2016 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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