wordpress 記事のカテゴリで子のみ取得

cat_is_ancestor_of

【WordPress】get_the_categoryで子カテゴリのみ取り出す方法

          <div class="cat">
          
          <?php 
  $cats = get_the_terms($post->ID,'koe_chiiki');
  //子カテゴリを取得
  $current_cat = '';
  foreach ($cats as $cat) {
    if (!$current_cat || cat_is_ancestor_of($current_cat, $cat)) {
      $current_cat = $cat;
    }
  }
  // 子カテゴリを出力
  echo $current_cat->name;
?>
          
          </div>
<?php 
  $cats = get_the_category();
  //子カテゴリを取得
  $current_cat = '';
  foreach ($cats as $cat) {
    if (!$current_cat || cat_is_ancestor_of($current_cat, $cat)) {
      $current_cat = $cat;
    }
  }
  // 子カテゴリを出力
  echo "<a href=".get_category_link($current_cat->term_id).">".$current_cat->name."</a>";
?>