//最上位のカテゴリを取得(投稿IDから)
function get_term_ancestor ( $post_id = ”, $extree = ”, $tax_name = ‘category’ ) {
// [$post_id = 投稿ID],
// [$extree = 含めないカテゴリツリーのIDまたはスラッグ],
// [$tax_name = タクソノミ名]
if ( empty ( $post_id ) ) $post_id = get_post()->ID;
if ( $extree && !is_numeric( $extree ) ) $extree = get_term_by( ‘slug’, $extree, $tax_name )->term_id;
$terms = get_the_terms( $post_id, $tax_name );
if ($terms) :
foreach ( $terms as $current_term ) :
if ( $current_term->term_id !== $extree && !isset( $tia ) ) { // $extreeが親ではない場合
$req_id = $current_term->term_id;
break;
}
endforeach;
endif;
if ( $req_id ) return get_term_ancestor_by_term( $req_id, $tax_name );
else return false;
}