wordpressテーマをカスタマイズしていて、一番使うのが、カテゴリー系の関数ではないでしょうか?
あの時、どんな関数使った?→過去のテーマを見に行く。
そんなことばかり繰り返しているので、備忘録としてここに書いておくことにししました。
カテゴリーを取得
リンク付きのカテゴリー
the_category();
デフォルトのまま使うと「post-categories」というクラスの付いたリスト形式で表示されます。
the_category(',');
のように、区切り文字を指定してあげるとよいでしょう。
リンクなしのカテゴリー
$cats = get_the_category();
foreach($cates as $cat):
echo $cat->cat_name;
endforeach;
カテゴリーの一覧を表示
<ul>
<?php wp_list_categories(array(
'title_li' =>'', //デフォルトで出力されるタイトルを非表示
));?>
</ul>
タグを取得
リンク付きのタグ
the_tags();
このまま使うと、先頭に「タグ: 」という文字付きで、カンマ区切りでタグの一覧を表示します。
the_tags(',');
のように、区切り文字を指定してあげた方がいいです。
リンクなしのタグ
$tags = get_the_tags();
if($tags): //タグがあったら
foreach($tags as $tag):
echo $tag->name;
endforeach;
endif;
カテゴリーと違って、タグを持っていないこともあるので、if分でタグあったらという条件分岐をつけないと、エラーになる可能性があります。
タグの一覧(タグクラウド)
wp_tag_cloud();
タグクラウドですので、数によって文字サイズが変動します。
ちょっと、それはカッコ悪いので、Codexを参考に下記のようにカスタマイズして使ってます。
wp_tag_cloud(array(
'smallest' => 1, //件数が少ないタグのフォントサイズ
'largest' => 1, //件数が多いタグのフォントサイズ
'unit' => 'em', //フォントサイズの単位
'orderby' => 'count', //並び順 件数の多い順にしてます
'order' => 'DESC',
'number' => 0, //表示数 0は全て表示
));
カスタムタクソノミー(カスタム分類)の取得
カスタム投稿などで使用するカスタムタクソノミー(カテゴリーやタグ)には、それ用の関数を使わなければいけません。
リンク付きのターム
カテゴリーもタグも使い方は同じです。
echo get_the_term_list($post->ID, カスタムタクソノミー名, $before, $sep, $after);
カスタムタクソノミー名が「custom_cat」、区切り文字を「,」にしたい場合
echo get_the_term_list($post->ID, custom_cat, '', ',', '');
「custom_cat」をリスト形式で表示したい場合
echo get_the_term_list($post->ID, custom_cat, '<ul><li>', '</li><li>', '</li></ul>');
リンクなしのターム
$terms = get_the_terms($post->ID, 'custom_cat');
foreach($terms as $term):
echo $term->name;
endforeach;
タームの一覧を表示
<ul>
<?php wp_list_categories(array(
'taxonomy' => 'custom_cat',//カスタム分類名
'title_li' =>'', //デフォルトで出力されるタイトルを非表示
));?>
</ul>
まとめ
いろいろ書いてみましたけど、結局、「カテゴリー」も「タグ」もカスタムタクソノミーの「category」「post_tag」なんですよ。
カスタムタクソノミーを取得、表示できればオールOKなんです。
親子関係を気にしなければ、カテゴリーもタグもカスタムタクソノミーも全部一緒です。
リンク付きで表示
■カテゴリ
echo get_the_term_list($post->ID, categry, '', ',', '');
■タグ
echo get_the_term_list($post->ID, post_tag, '', ',', '');
■カスタムタクソノミー(caustom_cat)
echo get_the_term_list($post->ID, custom_cat, '', ',', '');
リンクなしで表示
■カテゴリ
$terms = get_the_terms($post->ID, 'category');
■タグ
$terms = get_the_terms($post->ID, 'post_tag');
■カスタムタクソノミー(caustom_cat)
$terms = get_the_terms($post->ID, 'custom_cat');
foreach($terms as $term):
echo $term->name;
endforeach;
一覧を表示
■カテゴリ
<ul>
<?php wp_list_categories(array(
'taxonomy' => 'category',//タクソノミー
'title_li' =>'', //デフォルトで出力されるタイトルを非表示
));?>
</ul>
■タグ
<ul>
<?php wp_list_categories(array(
'taxonomy' => 'post_tag',//タクソノミー
'title_li' =>'', //デフォルトで出力されるタイトルを非表示
));?>
</ul>
■カスタムタクソノミー(caustom_cat)
<ul>
<?php wp_list_categories(array(
'taxonomy' => 'custom_cat',//タクソノミー
'title_li' =>'', //デフォルトで出力されるタイトルを非表示
));?>
</ul>
タグクラウド
■カテゴリ
wp_tag_cloud(array(
'taxonomy' => 'category',//タクソノミ―
));
■タグ
wp_tag_cloud(array(
'taxonomy' => 'post_tag',//タクソノミ―
));
■カスタムタクソノミー(caustom_cat)
wp_tag_cloud(array(
'taxonomy' => 'custom_cat',//タクソノミ―
));