今の自分にできることを、集中し全力を尽くせ

info@example.com 000-000-0000

Do your best !

今の自分にできることを、集中し全力を尽くせ

複数カテゴリーに属する場合に、1つだけ表示する

一覧ページ等、全部のカテゴリーを表示してしまうとレイアウトが崩れてしまったり都合が悪い場合に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/

https://bambooworks.co/wordpress-category-show-only-one/

Side Contents

Category List

Archive List

タグ