我会亲自创建三个custom taxonomies 而不是对类别/子类别执行此操作,那么这就不是问题了。
要对类别/子类别执行此操作,请从父类别的名称/ID开始,循环遍历每个父类别,然后在其中循环遍历与帖子关联的术语,并对照顶级类别的ID检查术语的父ID:
// names / IDs of parents
$parents = array(
\'Brand\' => 42,
\'Region\' => 22,
\'Grape\' => 18
);
// get post categories
$categories = get_the_terms( $post->ID, \'category\' );
// output top level cats and their children
foreach( $parents as $parent_name => $parent_id ):
// output parent name and link
echo \'<a href="\' . get_term_link( $parent_id, \'category\' ) . \'">\' . $parent_name . \'</a>: \';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
if( $parent_id == $category->parent ):
// put link in array
$links[] = \'<a href="\' . get_term_link( $category ) . \'">\' . $category->name . \'</a>\';
endif;
endforeach;
// join and output links with separator
echo join( \', \', $links );
endforeach;
编辑-动态获取顶级术语:
// get top level terms
$parents = get_terms( \'category\', array( \'parent\' => 0 ) );
// get post categories
$categories = get_the_terms( $post->ID, \'category\' );
// output top level cats and their children
foreach( $parents as $parent ):
// output parent name and link
echo \'<a href="\' . get_term_link( $parent ) . \'">\' . $parent->name . \'</a>: \';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
if( $parent->term_id == $category->parent ):
// put link in array
$links[] = \'<a href="\' . get_term_link( $category ) . \'">\' . $category->name . \'</a>\';
endif;
endforeach;
// join and output links with separator
echo join( \', \', $links );
endforeach;