【wordpress】指定したタームの子タームの情報を取得する

参考サイト

https://ziyudom.com/term-children/

 

 

//タクソノミーネーム
$taxonomyName = "brands";
//親タームだとprentが0なのでこれを指定
$args = array(
    'parent' => 0
);
//親を取得
$terms = get_terms($taxonomyName,$args);
foreach ($terms as $term) {
    echo "<h2 style='font-size:30px;margin:20px 0;'>$term->name</h2>";
    //親のIDを取得できた
    $parentId = $term->term_id;
 
    /*ここから親タームのIDがそれぞれ取得できるので、そこから子タームのリストを作る*/
    //さっきはparentが0だったが、こんかいはprentが親IDの場合の条件
    //
    $childargs = array(
        'parent' => $parentId,
        'hide_empty' => false//投稿がない場合も隠さずにだす
    );
    $childterms = get_terms($taxonomyName,$childargs);
    foreach ($childterms as $childterm) {
        $targetSlug = $childterm->slug;
        echo "<h2 style='font-size:16px;margin:10px 0;'>$childterm->name</h2>";//子タームの名前
        echo "<p style='font-size:12px; margin-bottbom: 10px;'>".$targetSlug."</p>";//子タームのスラッグ
        //子ターム情報が取得できたので、ここからget_posts用に準備
        $postargs = array(
            'post_type' => 'shop',//さっきのbrandsタクソノミーを使ってる“投稿”のポストタイプ
            'tax_query' => array(
                array(
                    'taxonomy' => $taxonomyName,
                    'field' => 'slug',//フィールドをslugにしておくterm_idとかでも良いはず
                    'terms' => $targetSlug//上で準備してある$childterm->slug
                )
            )
        );
        //あとはいつも通り取得
        $postslist = get_posts( $postargs );
 
        foreach ( $postslist as $post ) : setup_postdata( $post );
        echo "<li>".get_the_title()."</li>";
 
        endforeach;
        wp_reset_postdata();
    }
}