LoginSignup
3
3

More than 5 years have passed since last update.

指定したカテゴリの最上位の親カテゴリを取得する関数

Posted at

カテゴリIDを指定するだけで最上位の親カテゴリの情報を返してくれる関数です。

    function get_top_categoryData($cat_id){

        $category_data=get_category($cat_id);

        while($category_data->category_parent != 0){
            $category_data=get_category($category_data->category_parent);
        }

        return $category_data;

    }

指定したIDが最上位の場合はそのまま指定したIDのカテゴリ情報を返します。

 

利用例
取得したカテゴリの最上位カテゴリの名称を表示
※例なので、カテゴリは記事にひとつのみ設定されている想定です。

$post_category = get_the_category();

$post_top_category = get_top_categoryData($post_category[0]->term_id);

echo $post_top_category->name;

 
親カテゴリによって表示を切り替える機会などが多いので、そういった場合に使うと記述量が減るので便利です。

3
3
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
3
3