カテゴリ名/スラグを取得する方法 | WordPress開発

※当サイトはアフィリエイト広告を利用しています。

WordPressで特定のカテゴリ名やスラグを取得する方法を紹介します。

カテゴリ名やスラグを取得することで、カテゴリページを作成する際や特定のカテゴリに属する投稿を取得する際に役立ちます。

WordPressには、カテゴリ名やスラグを取得するための関数が用意されていますので、それらを使って取得する方法を解説します。
スポンサーリンク


カテゴリ名/スラグを取得する方法

カテゴリ名を取得するにはget_the_category()を使用します。

get_the_categoryはカテゴリ関連の情報を持つオブジェクトの配列になります。

サンプルコードは以下になります。
$catList = get_the_category();
var_dump($catList);
/*
Reuslt:

array (size=1)
  0 => 
    object(WP_Term)[695]
      public 'term_id' => int 1
      public 'name' => string 'Uncategorized' (length=13)
      public 'slug' => string 'uncategorized' (length=13)
      public 'term_group' => int 0
      public 'term_taxonomy_id' => int 1
      public 'taxonomy' => string 'category' (length=8)
      public 'description' => string '' (length=0)
      public 'parent' => int 0
      public 'count' => int 1
      public 'filter' => string 'raw' (length=3)
      public 'cat_ID' => int 1
      public 'category_count' => int 1
      public 'category_description' => string '' (length=0)
      public 'cat_name' => string 'Uncategorized' (length=13)
      public 'category_nicename' => string 'uncategorized' (length=13)
      public 'category_parent' => int 0
*/

このオブジェクトのnameにカテゴリ名が、slugにカテゴリスラグが入っています。

よって、これらを参照すればカテゴリ名とカテゴリスラグが取得できます。

以下、1個目のカテゴリのカテゴリ名とカテゴリスラグを取得するサンプルコードです。
$catList = get_the_category();
if(count($catList) > 0) {
    $catName = $catList[0]->name;
    $catSlug = $catList[0]->slug;
} else {
    $catName = "undefined";
    $catSlug = "undefined";
}

まとめ

この記事ではWordPressで特定のカテゴリ名やスラグを取得する方法を紹介しました。