我有一个祖父母类别,由子女和孙子组成,如下:
03
- Child Cat 02
- Grandchild Cat 01
- Grandchild Cat 02
- Grandchild Cat 03我想循环这些在一个主要祖父母类别页面,并显示每个孩子的标题,与孙辈下面的链接。
到目前为止,我看到的是所有的孩子和孙子,但没有区分这两种.
<?php
$this_category = get_category($cat);
$args = (array (
'orderby'=> 'id',
'depth' => '1',
'show_count' => '0',
'child_of' => $this_category->cat_ID,
'echo' => '0'
));
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo $category->name
} ?>我需要一条规则如果我有孩子..。
发布于 2021-03-12 11:34:08
通过检查类别是否有父类,这相对比较简单。
<?php
$this_category = get_category($cat);
$args = (array (
'orderby'=> 'id',
'depth' => '1',
'show_count' => '0',
'child_of' => $this_category->cat_ID,
'echo' => '0'
));
$categories = get_categories( $args );
foreach ( $categories as $category ) {
if (!$category->parent) {
echo 'Has no parent';
}
echo $category->name;
} ?>另外一种递归方法,取决于您需要什么。
<?php
$this_category = get_category($cat);
function category_tree(int $categoryId = 0) {
$categories = get_categories([
'parent' => $categoryId,
'echo' => 0,
'orderby' => 'id',
'show_count' => 0
]);
if ($categories) {
foreach ($categories as $category) {
echo '<ul>';
echo '<li>';
echo $category->name;
category_tree($category->term_id);
}
}
echo '</li></ul>';
}
category_tree($this_category->cat_ID);https://stackoverflow.com/questions/66599045
复制相似问题