カスタム投稿タイプのカスタムタクソノミー&タームテンプレートを作ろう
カスタム投稿タイプの記事一覧は少ないコードで作れるため難易度は高くはありませんが、カスタムタームは今まで使っていないコードが必要になるため、難易度が上がります。
一例を使ってカスタムタームテンプレートを作り方を紹介します。
仕様
- タクソノミートップは全記事表示
- タームページはターム記事を表示
設定例
- カスタム投稿名
shopguide
- カスタムタクソノミー名
shopguide_category
全コード
<?php get_header() ?>
<?php
// タクソノミー名を設定
$tax_name = 'shopguide_category';
// ターム一覧を取得
$terms = get_terms($tax_name, 'hide_empty=0');
// タームページではない場合、タームの全記事を取得
if( !$term ){
$term = array();
foreach ( $terms as $myterm ){
array_push($term, $myterm->slug);
}
}
$args = array(
'post_type' => 'shopguide',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => $tax_name,
'field' => 'slug',
'terms' => $term,
'include_children' => true,
)
)
);
$the_query = new WP_Query( $args );
?>
<h1>アーカイブタイトル</h1>
<h2>ターム一覧</h2>
<ul>
<?php foreach ( $terms as $myterm ): ?>
<li<?php if($myterm->slug == $term) echo ' class="current"'; ?>><a href="<?php echo get_term_link( $myterm, $taxonomy ); ?>"><?php $myterm->name ?></a></li>
<?php endforeach; ?>
</ul>
<h2>記事一覧</h2>
<?php if ($the_query->have_posts()): ?>
<div class="item">
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<div class="item">
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
<p><?php get_the_terms($post->ID, $tax_name)[0]->name; ?></p>
</div>
<?php endwhile; ?>
</div>
<?php else: ?>
<p>記事はありません</p>
<?php endif; wp_reset_postdata(); ?>
<?php get_footer() ?>
事前設定
大きく事前設定と表示用のコードに分けています。
事前設定でやること
- タクソノミーのタームリスト用のリスト取得
- 全記事orタームに所属している記事取得
<?php
// タクソノミー名を設定
$tax_name = 'shopguide_category';
// ターム一覧を取得
$terms = get_terms($tax_name, 'hide_empty=0');
// タームページではない場合、タームの全記事を取得
if( !$term ){
$term = array();
foreach ( $terms as $myterm ){
array_push($term, $myterm->slug);
}
}
$args = array(
'post_type' => 'shopguide',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => $tax_name,
'field' => 'slug',
'terms' => $term,
'include_children' => true,
)
)
);
$the_query = new WP_Query( $args );
?>
タクソノミーのタームリストを表示
カテゴリー一覧のタームverです。
<?php if($myterm->slug == $term) echo ' class="current"'; ?>
は、今開いているカテゴリーのページだった場合class="current"
を付与するようにしています。
<h2>ターム一覧</h2>
<ul>
<?php foreach ( $terms as $myterm ): ?>
<li<?php if($myterm->slug == $term) echo ' class="current"'; ?>><a href="<?php echo get_term_link( $myterm, $taxonomy ); ?>"><?php $myterm->name ?></a></li>
<?php endforeach; ?>
</ul>
タクソノミー&タームの記事一覧を表示
記事表示部分です。
表示要素
- 記事タイトル
- ターム名
<h2>記事一覧</h2>
<?php if ($the_query->have_posts()): ?>
<div class="item">
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<div class="item">
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
<p><?php get_the_terms($post->ID, $tax_name)[0]->name; ?></p>
</div>
<?php endwhile; ?>
</div>
<?php else: ?>
<p>記事はありません</p>
<?php endif; wp_reset_postdata(); ?>