- Web制作
WordPressのカスタム投稿の所属するタームをタブと連動して動的に出力

WordPressのカスタム投稿は、ターム(カテゴリやタグ)を割り当てることができます。
タームはその数だけタブで分類して動的に出力することで、ユーザーが目的の投稿を簡単に見つけられるようになります。
カスタム投稿「information」
カスタムタクソノミー「information_cat」
タームとタブを連動して出力します。
PHP
<div class="tab_box">
<div class="btn_area">
<div class="tab_btn active">すべて</div>
<?php
$terms = get_terms('information_cat');
foreach ($terms as $term) {
echo '<div class="tab_btn">' . esc_html($term->name) . '</div>'; // タームタイトル
}
?>
</div>
<div class="panel_area">
<div class="tab_panel active">
<ul class="list">
<?php
$args = array(
'post_type' => 'information',
'posts_per_page' => 3,
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
while ($the_query->have_posts()) : $the_query->the_post();
?>
<li class="item">
<a href="<?php the_permalink() ?>">
<div class="date">
<?php the_time('Y.m.d') ?>
</div>
<?php
if ($terms = get_the_terms($post->ID, 'information_cat')) {
foreach ($terms as $term) {
echo '<div class="cat">' . $term->name . '</div>';
}
}
?>
<h4 class="postttl">
<?php the_title(); ?>
</h4>
</a>
</li>
<?php endwhile;
endif; ?>
<?php wp_reset_postdata(); ?>
</ul>
</div>
<?php
$terms = get_terms('information_cat');
foreach ($terms as $term) :
?>
<div class="tab_panel">
<ul class="list">
<?php
$args = array(
'post_type' => 'information',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'information_cat',
'field' => 'slug',
'terms' => $term->slug,
),
),
);
$my_posts = get_posts($args);
?>
<?php foreach ($my_posts as $post) : setup_postdata($post); ?>
<li class="item">
<a href="<?php the_permalink() ?>">
<div class="date">
<?php the_time('Y.m.d') ?>
</div>
<?php
if ($terms = get_the_terms($post->ID, 'information_cat')) {
foreach ($terms as $term) {
echo '<div class="cat">' . $term->name . '</div>';
}
}
?>
<h4 class="postttl">
<?php the_title(); ?>
</h4>
</a>
</li>
<?php
wp_reset_postdata();
endforeach;
?>
</ul>
</div>
<?php
endforeach;
?>
</div>
</div>
CSS(タブ実装)
.tab_box .panel_area .tab_panel {
display: none;
}
.tab_box .panel_area .tab_panel.active {
display: block;
}
JS(タブ実装)
<script>
$('.tab_box .tab_btn').click(function () {
var index = $('.tab_box .tab_btn').index(this);
$('.tab_box .tab_btn, .tab_box .tab_panel').removeClass('active');
$(this).addClass('active');
$('.tab_box .tab_panel').eq(index).addClass('active');
});
</script>

名古屋の Web 制作会社で 9 年半働いた後フリーランスに。中小企業のWEBサイト制作実績 120 サイト以上。ディレクション、デザイン、コーディング、WordPress 構築まで手掛けます。Web制作に関わる情報やワーケーション日記などを執筆しています。