0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressで親カテゴリーを再帰的に取得

0
Posted at

よく書く処理なので。

WP_Termオブジェクトを配列で返す場合

function find_ancestor_categories($category_id, $categories = []) {
  $category = get_category($category_id);
  $categories[] = $category;
  if($category->parent) {
    $categories = find_ancestor_categories($category->parent, $categories);
  }
  return $categories;
}

term_idを配列で返す場合

function find_ancestor_category_ids($category_id, $category_ids = []) {
  $category = get_category($category_id);
  $category_ids[] = $category->term_id;
  if($category->parent) {
    $category_ids = find_ancestor_category_ids($category->parent, $category_ids);
  }
  return $category_ids;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?