taxonomyページで子タームがある場合はターム情報を出力し、子タームがない場合は登録情報を出力する
備忘録として残します。
<?php $tax = get_queried_object();
$tax_name = $tax->taxonomy;
$term_id = $tax->term_id;
$check = get_term_children($term_id, $tax_name);
if($check): //子タームがある場合 ?>
<ul class="has_child">
<?php $termchildren = get_term_children($term_id, $tax_name);
foreach($termchildren as $child){
$term = get_term_by('id', $child, $tax_name);
$term_id = $term->term_id;
$term_link = get_term_link($term);
$term_name = $term->name;
$termchild_description = strip_tags(term_description($term_id));
$termchild_description = wp_html_excerpt($termchild_description, 60);
if(mb_strlen($termchild_description) < 60){
$description_excerpt = $termchild_description;
} else {
$description_excerpt = $termchild_description.'…';
} ?>
<li><a href="<?php echo $term_link; ?>">
<strong><?php echo $term_name; ?></strong><br>
<span><?php echo $$description_excerpt; ?></span>
</a></li>
<?php } ?>
</ul>
<?php else: //子タームがない場合 ?>
<ul class="no_child">
<?php while(have_posts()): the_post();
$child_description = mb_substr(get_the_excerpt(), 0, 60);
if(mb_strlen($child_description) < 60) {
$child_description_excerpt = $child_description;
} else {
$child_description_excerpt = $child_description.'…';
} ?>
<li><a href="<?php the_permalink(); ?>">
<strong><?php the_title(); ?></strong><br>
<span><?php echo $child_description_excerpt; ?></span>
</a></li>
<?php endwhile;
endif; ?>
子タームの有無を判断する方法について解説
1行目:
get_queried_object() とは、情報オブジェクトを取得する関数です。taxonomy.php で使用しているので、ターム情報を取得してます。
2、3行目:
get_queried_object() で取得した情報より、タクソノミー名とタームIDを取得します。
4行目:
get_term_childrent() とは、指定した親タームに対して、それにぶらさがる子タームを取得する関数です。ここで値を取得できるかどうかで子タームの有無が判断できます。
6行目:
4行目で値を取得できた(子タームあり)場合のifです。
28行目:
4行目で値を取得できなかった(子タームなし)場合のifです。
MovableType/WordPressを使ったホームページ制作、機能追加や設置代行などの改修、システム開発、サイトの保守を手掛けております。
アナタが実現させたい機能、やりたい事をお聞かせいただけませんか? そのイメージを一緒に実現しましょう!
お問い合わせは以下のページから!!