Wordpress 显示 parent 类别作为标题,下方有 children

Wordpress display parent category as heading with children underneath

我有一个祖父母类别设置 children 和 grandchildren 像这样:

  1. 猫爷爷
    • Child 类别 01
      • 大child 猫 01
      • 大child猫 02
      • 大child猫 03
    • Child 猫 02
      • 大child 猫 01
      • 大child猫 02
      • 大child猫 03

我想在主祖父母类别页面上循环浏览这些内容并显示每个 child 标题,并在下方显示祖children 链接。

到目前为止,我有这个显示所有 children 和 grandchildren,但没有区分两者...

        <?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
        
        } ?>

如果 children...

我需要一个规则

通过检查类别是否有父类别来识别相对简单

<?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);