うさぎのイラスト

ネットアンサー55備忘録

web技術を書いていきます

カテゴリータグの抽出

-2015年07月18日-
投稿のカテゴリーの呼び出しは以下です。
1<?php
2$postcategories =get_the_category();
3if ($postcategories) {
4     foreach($postcategories as $tag) {
5          echo '<span class="' . $tag->slug . '">' . $tag->name . '</span>';
6    }
7}  
8?>
カスタム投稿のカテゴリーの呼び出しは以下です。
1<?php
2$cat=(get_post_type_object(get_post_type())->name).'_cat';
3if ($terms = get_the_terms($post->ID, $cat)) {
4    foreach ( $terms as $term ) {
5    echo '<span class="' . $term->slug . '">' . $term->name . '</span>';
6    }
7}
8?>
抽出されたカテゴリータグにはclassが付与されます。
cssで色をつけましょう。下記に例を示します。
1/*wordpressのカテゴリー*/
2.category_box_box .custom_post,
3.category_box_box .tm,
4.category_box_box .theme,
5.category_box_box .function,
6.category_box_box .plugin,
7.category_box_box .setting{
8        background-color:#3B7689;
9}
10 
11/*illustratorのカテゴリー*/
12.category_box_box .conv,
13.category_box_box .object,
14.category_box_box .chara,
15.category_box_box .materi{
16        background-color:#C95C47;
17}