要按层次排序,请尝试向函数中添加排序函数。php(或插件)。
// This will sort and place everything in the $into array
function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0) {
foreach ($cats as $i => $cat) {
if ($cat->parent == $parentId) {
$cat->posts = array();
$into[$cat->term_id] = $cat;
unset($cats[$i]);
}
}
foreach ($into as $topCat) {
$topCat->children = array();
sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
}
}
现在,在显示端,您可以抓取所有类别并以第二个父名称显示它们。
$terms = get_the_terms( $product->get_id(), \'product_cat\' );
if ( $terms ) {
$listItems = \'\';
$sortedTerms = array(); // empty array to hold the sorted terms
sort_terms_hierarchically( $terms, $sortedTerms ); // sort everything
foreach( $sortedTerms as $parent) {
if ( empty( $parent->children ) ) continue;
foreach( $parent->children as $child ) {
$listItems .= \'<li>\' . $child->name . \', \' . $parent->name . \'</li>\';
}
}
}
// Display the list
if ( !empty( $listItems ) ) {
echo \'<ul>\' . $listItems . \'</ul>\';
}
希望这能更好地回答您的问题!