一覧ページ等、全部のカテゴリーを表示してしまうとレイアウトが崩れてしまったり都合が悪い場合に1つだけ取得する場合のソースです。 配列の1番目のカテゴリー[0]を取得します。
下記のPHPは自分でカスタマイズしまいた。
カテゴリー表示リンクなし背景あり
<?php
$categories = get_the_category();
if ( $categories ) {
echo '<span class="'.$categories[0]->slug.'">' .$categories[0]->name.'</span>';
}
?>リンク有りの場合
<?php
$categories = get_the_category();
if ( $categories ) {
echo '<a href="'.esc_url(get_category_link($categories[0]->term_id)).'">'.$categories[0]->name.'</a> ';
}
?>リンク有りの場合でaタグにスラッグを追加(CSSで色分け等をするのに便利!)
<?php
$categories = get_the_category();
if ( $categories ) {
echo '<a href="'.esc_url(get_category_link($categories[0]->term_id)).'" class="'.$categories[0]->slug.'">'.$categories[0]->name.'</a> ';
}
?>リンク無しの場合
<?php
$categories = get_the_category();
if ( $categories ) {
echo $categories[0]->name;
}
?>参考サイト一覧
https://illustswitch.com/wp/categories-post-belongs-to-onecategory/