目次
カスタムタクソノミーの親子関係を保ったままループしたい
参考:http://www.studiobusstop.com/1112/
<?php
$target_post = '★投稿タイプslug★';
$target_post_cat = '★タクソノミーslug★';
$post_count = -1;
$cat_args = array(
'parent' => 0, //トップレベルのタームのみ
'hierarchical' => 0, //子タームを含めない
'hide_empty' => 0 //全部出す
);
$cats = get_terms($target_post_cat, $cat_args);
foreach ($cats as $cat):
?>
<?php
$target_cat_name = esc_html($cat->name);//親カテゴリ名
$target_cat_slug = esc_html($cat->slug);//親カテゴリスラッグ
?>
<h3 id="<?php echo $target_cat_slug; //親カテゴリスラッグ?>"><?php echo $target_cat_name;//親カテゴリ名 ?></h3>
<?php $child_cats = get_terms($target_post_cat, 'hierarchical=0&hide_empty=0&parent=' . $cat->term_id); ?>
<?php if ($child_cats) : ?>
<?php foreach ($child_cats as $child_cat): ?>
<?php
$child_cat_name = esc_html($child_cat->name);//子カテゴリ名
$target_cat_slug = esc_html($child_cat->slug);//子カテゴリスラッグ
?>
<h4><?php echo $child_cat_name; //子カテゴリ名?></h4>
<?php
$args = array(
'post_type' => array($target_post),
'taxonomy' => $target_post_cat,
'term' => $target_cat_slug,
'post_status' => 'publish',
'posts_per_page' => $post_count, // 表示するページ数
'orderby' => 'menu_order',
//'order' => 'DESC' // 並び順
);
$my_query = new WP_Query($args);
?>
<?php if ($my_query->have_posts()) : ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><?php the_title();//投稿タイトル ?></li>
<?php if ($child_cat->description) ://タクソノミー説明文 ?>
<li>
<?php echo esc_html($child_cat->description);//タクソノミー説明文 ?>
</li>
<?php endif; ?>
<?php endwhile; ?>
</ul>
<?php else: ?>
<ul>
<?php if ($child_cat->description) : ?>
<li>
<?php echo esc_html($child_cat->description);//タクソノミー説明文 ?>
</li>
<?php endif; ?>
</ul>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>
上記をarchive-{post_type}.phpに書いて出力した後、タクソノミー順がかなり大事だったので、追加でCustom Taxonomy Order NEを使いました。
‘order’ => ‘DESC’ // 並び順 をコメントアウトしたのは、こちらで設定した順で表示したかったため。
子カテゴリがあるときとない時で、動作を変えたいとき
参考:https://www.sendai-kuraso.com/work/wordpress/thum-wp-childterm.html
$target_cat_name = esc_html($cat->name);//親カテゴリ名
$target_cat_slug = esc_html($cat->slug);//親カテゴリスラッグ
//このタイミングで下記を追加
$check = get_term_children($cat->term_id, "$target_post_cat")//子カテゴリの有無;
<?php if ($check): // 子カテゴリがあるなら… ?>
//この前に↑↑を追加
<?php $child_cats = get_terms($target_post_cat, 'hierarchical=0&hide_empty=1&parent=' . $cat->term_id); ?>
<?php if ($child_cats) : ?>

コメント