仅显示自定义层次分类的子项

时间:2016-10-01 作者:user3009948

我试图只列出所选父类别的子类别。以下代码列出了所有子级。我只希望能够更改父对象的id或其他内容,以便仅列出所选父对象中的子对象。

<?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>\';

?>   
如果有人能帮忙,请。谢谢

1 个回复
最合适的回答,由SO网友:cowgill 整理而成

根据我们的评论讨论,您正在一个贴子页面上的边栏小部件(接受php代码)中使用代码。

结果比预期的要复杂得多。不过,这应该行得通。

<?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>\';
}
?>