自分用にメモ。
【WordPress】カテゴリーの設定
HTML
あらかじめWordPressのカテゴリーで用意されているクラスをつけておくと、後でHTMLからWordPress化するのがスムーズになる。
<ul class="post-categories">
<li>
<a href="">
<span class="entry-label">カテゴリ</span>
</a>
</li>
</ul>
CSS
「entry-label」に対してスタイルを当ててあげる。
.entry-label {
display: inline-block;
height: 25px;
line-height: 25px;
width: 130px;
text-align: center;
margin-left: 40px;
color: #fff;
font-size: 16px;
}
PHP
これで管理画面からカテゴリーを選択したら反映されるようになる。
<div class="categori">
<?php
$args = array(
'post_type' => 'post', //カスタム投稿タイプを指定
'posts_per_page' => 10, //表示する記事数
);
$news_query = new WP_Query( $args ); //サブループを変数に格納
if ( $news_query->have_posts() ) :
while ( $news_query->have_posts() ) :
$news_query->the_post();
?>
<?php
$this_categories = get_the_category();
if ( $this_categories ) {
$this_category_color = get_field( 'color', 'category_' . $this_categories[0]->term_id );
$this_category_name = $this_categories[0]->name;
}
?>
<div class="categori__item">
<div class="categori__item__info">
<time datetime="<?php the_time('Y-m-d'); ?>"><?php the_field('categori-date'); ?></time>
<ul class="post-categories">
<li>
<?php echo'<a href="' . get_category_link($this_categories[0]->term_id) . '"><span class="entry-label" style="' . esc_attr( 'background:' . $this_category_color ) . ';">' . esc_html( $this_category_name ) . '</span></a>';?>
</li>
</ul>
</div>
<div class="categori__item__info__title">
<a href=""><?php the_title(); ?></a>
</div>
</div>
<?php endwhile;
endif;
wp_reset_postdata(); //サブループを抜ける
?>
</div>



