WordPressのLightningでカテゴリーボタンを複数表示する
はじめに
Lightningでは、投稿のカテゴリーは1つのみ表示するようになっています。

これを以下のように複数表示する方法について、ご紹介していきたいと思います。

手順
WordPress管理画面から[外観] – [テーマエディター]を選択します。

テーマファイルから「meta.php」を選択します。

最後のPHPソースコード部を以下のように書き換え、[ファイルの更新]ボタンをクリックします。先頭のカテゴリ「$terms[0]」のみ出力している箇所をforeachループで全カテゴリ分出力するように変更しています。
変更前
<?php
$taxonomies = lightning_get_display_taxonomies();
if ( $taxonomies ) :
// get $taxonomy name
// $taxonomy = key( $taxonomies );
foreach ( $taxonomies as $key => $value ) {
$taxonomy = $key;
break;
}
$terms = get_the_terms( get_the_ID(), $taxonomy );
$term_url = esc_url( get_term_link( $terms[0]->term_id, $taxonomy ) );
$term_name = esc_html( $terms[0]->name );
$term_color = '';
if ( class_exists( 'Vk_term_color' ) ) {
$term_color = Vk_term_color::get_term_color( $terms[0]->term_id );
$term_color = ( $term_color ) ? ' style="background-color:' . $term_color . ';border:none;"' : '';
}
echo '<span class="entry-meta_items entry-meta_items_term"><a href="' . $term_url . '" class="btn btn-xs btn-primary entry-meta_items_term_button"' . $term_color . '>' . $term_name . '</a></span>';
endif;
?>
変更後
<?php
$taxonomies = lightning_get_display_taxonomies();
if ( $taxonomies ) :
// get $taxonomy name
// $taxonomy = key( $taxonomies );
foreach ( $taxonomies as $key => $value ) {
$taxonomy = $key;
break;
}
$terms = get_the_terms( get_the_ID(), $taxonomy );
foreach($terms as $term) {
$term_url = esc_url( get_term_link( $term->term_id, $taxonomy ) );
$term_name = esc_html( $term->name );
$term_color = '';
if ( class_exists( 'Vk_term_color' ) ) {
$term_color = Vk_term_color::get_term_color( $term->term_id );
$term_color = ( $term_color ) ? ' style="background-color:' . $term_color . ';border:none;"' : '';
}
echo '<span class="entry-meta_items entry-meta_items_term"><a href="' . $term_url . '" class="btn btn-xs btn-primary entry-meta_items_term_button"' . $term_color . '>' . $term_name . '</a></span>';
}
endif;
?>
次に、テーマファイルから「スタイルシート(style.css)」を選択します。

以下のコードを追記し、[ファイルの更新]ボタンをクリックします。
.entry-meta_items_term {
margin-right:3px;
}
@media screen and (max-width: 767px) {
.entry-meta .entry-meta_items_term {
display: unset;
}
}
ここでは、
- カテゴリー間の表示に隙間をあける
- スマホ表示時にカテゴリーを1行で表示する
の2点を対応しています。
投稿者プロフィール

- 東京在住のフリーランスエンジニア
最新の投稿
AWS2020.11.05AWS CLI コマンドまとめ ~S3編~
AWS2020.11.02AWS コマンドラインインターフェイス(CLI)をインストールする~Windows編~
その他2020.10.30Chromeでクロスドメインiframe内の要素にアクセスする
AWS2020.10.29AWS API GatewayのREST APIでモックを作成する