しんぷるハックではカテゴリごとにレイアウトを変更しています。↑こんな感じでアイキャッチの背景画像やアイキャッチ周りの枠線、リンクホバー時の背景色変更などがそれにあたります。
これは、WordPressの独自変数とCSSを用いて実現していますが、その方法をちょっと紹介しておきます。
1.ショートコードを用いてクラスを動的に出力する。
functions.phpに以下のコードを追加します。// カテゴリ情報取得関数
function getCategoryInfo($target)
{
extract(shortcode_atts(array('target' => 0,), $target));
$cat = get_the_category();
$cat_info = $cat[0];
// 第1カテゴリ名を取得
if ($target == "name") {
return $cat_info->cat_name;
// 第1カテゴリIDを取得
} else if ($target == "id") {
return $cat_info->cat_ID;
}
}
add_shortcode('getCategoryInfo', 'getCategoryInfo');
次にindex.phpやsingle.phpなど、レイアウトを変更したい場所を変更します。こんな感じ。
">
「post_title_category」がカスタマイズ箇所にあたります。どういうことをしているかと言うと、PHPでエントリーごとのカテゴリIDを取得して(functions.php実装部)、HTMLに書き出す(index.phpやsingle.phpなど)ということをやってます。
2.CSSの正規表現を用いてレイアウトを整える。
最後にstyle.cssなどCSSファイルに手を加えます。HTMLに出力されるのは「post_title_category1」(1がカテゴリIDに該当)という形式なので以下の様に記載します。div[class*="post_title_category1"] a:hover {background-color: rgba(240,230,140, 0.9);}
div[class*="post_title_category2"] a:hover {background-color: rgba(217,229,255, 0.9);}
div[class*="post_title_category3"] a:hover {background-color: rgba(255,213,236, 0.9);}
div[class*="post_title_category4"] a:hover {background-color: rgba(255,219,201, 0.9);}
div[class*="post_title_category5"] a:hover {background-color: rgba(243,255,216, 0.9);}
div[class*="post_title_category6"] a:hover {background-color: rgba(0,240,120, 0.9);}
div[class*="post_title_category7"] a:hover {background-color: rgba(255,255,204, 0.9);}
div[class*="post_title_category8"] a:hover {background-color: rgba(96,144,239, 0.9);}
div[class*="post_title_category9"] a:hover {background-color: rgba(255,127,80, 0.9);}
.post_title_category20 a:hover {background-color: rgba(218,22,62, 0.9) !important;}
1行目を例に取って説明すると、divタグのclass要素にて「post_title_category1」を含む場合に限り、スタイルを編集しています。つまり、post_title_category1やpost_title_category10、post_title_category12、post_title_category100の場合にCSSが適用されます。
これで実装は完了です。
3.CSSの正規表現の書き方。
CSSの正規表現には「^」「$」「*」がありますが、それぞれの役割は以下の通りです。「^」は指定文字から始まる要素が該当
「$」は指定の文字で終わる要素が該当
「*」は指定の文字を含む要素が該当
今回は「*」を用いましたが、「^」でも問題ありません。というか「^」の方が利用方法としては正しいのですが、PHPにて「post_title_category」から始めるように実装しているため、より広義な「*」を使用しても問題ありません。