【WordPress】親カテゴリーで子カテゴリーをループ
目次
親カテゴリーに紐づく子カテゴリーの一覧を表示する方法
色々結構調べて実装できたので覚書程度で掲載します。
※参考記事忘れてしまいました…すみません。
コードを記載させて頂きます。
とりあえず内容まとめてみました。
サンプル
0,
// 子タームの投稿数を親タームに含める
'pad_counts' => false,
// 投稿記事がないタームは取得しない
'hide_empty' => true
);
// カスタム分類のタームのリストを取得
$terms = get_terms( $taxonomy , $args );
if ( count( $terms ) != 0 ) {
// 親タームのリスト $terms を $term に格納してループ
foreach ( $terms as $term ) {
// 親タームのURLを取得
$term = sanitize_term( $term, $taxonomy );
$term_link = get_term_link( $term, $taxonomy );
if ( is_wp_error( $term_link ) ) {
continue;
}
$slug = $term->slug;
// 親タームのURLと名称を出力
echo 'ここで親要素の内容が表示されます。htmlで記載して調整してください。' . esc_url( この中に取得したい内容(phpを記載) ) . '' . $term->name . '←カテゴリー名
';
$posts = get_posts( array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $slug
)
),
'posts_per_page' => -1,
));
foreach($posts as $post){
setup_postdata( $post );
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
$image_url_hon = '';
if ( $image_url ) {
$image_url_hon = $image_url[0];
}
?>
この部分でループしたい内容を記載。
子カテゴリーが表示されます。
ここより上がループ部分
まとめ
もし苦しんでいるかたがいたら参考になれば幸いです。