Search code examples
phpwordpresstaxonomycustom-taxonomytaxonomy-terms

WordPress: Get top level taxonomy by term ID


I've an ID of a custom taxonomy. Now I try to get the top level taxonomy of that ID.

For example, this is my taxonomy tree:

  • Cars (ID: 1)
    • Mercedes (ID: 2)
      • S-Class (ID: 3)

I try to get the ID from the first level (ID: 1) based on the ID 3.

I found a lot of examples but they don't work with only one given integer/ID.

For example this one:

function get_term_top_most_parent( $term_id, $taxonomy ) {
    $parent  = get_term_by( 'id', $term_id, $taxonomy );
    while ( $parent->parent != 0 ){
        $parent  = get_term_by( 'id', $parent->parent, $taxonomy );
    }
    return $parent;
}

I changed $term_id with 3 but it doesnt do anything.


Solution

  • After some testing I found a good answer here.

    My code looks like this now:

    $tax_ancestors = get_ancestors( $tax_first_id, 'product_cat' ); // $tax_first_id = 3
    if ( !empty($tax_ancestors)) : 
        $tax_last_id = end($tax_ancestors);
    else :
        $tax_last_id = $tax_first_id;
    endif;