Get parent term of any given term id in WordPress

Getting parent term of any given term id is bit complex, and WordPress doesn’t have any built in method for this. So, I have built a utility function to get top most or immediate parent of any given term id.

For example: If you want to get parent category name of any given category, sending that category id in the utility function will return either top most parent or immediate parent, depending on your choice. If provided category is not child of any category, then it will just return the name of provided category id.

function careless_get_parent_taxonomy( $term_id, string $taxonomy_name = 'category', bool $top_most = true ) {
    //term id is mandatory
    if ( !$term_id ) {
        return false;
    }

    //get parents
    $parents = get_ancestors( $term_id, $taxonomy_name, 'taxonomy' );

    //provided category is not child of any category
    if ( empty( $parents ) ) {
        $term = get_term( $term_id, $taxonomy_name );

        //term doesn't exist or error
        if ( !$term || is_wp_error( $term ) ) {
            return false;
        }

        return $term->name;
    }

    //get the top most parent
    if ( $top_most ) {
        //last item is the top most parent - so we reverse
        $parents = array_reverse( $parents );

        $parent_term = get_term( $parents[0], $taxonomy_name );
    } else {//get immediate parent
        //last item is the top most parent - so second item is immediate parent 
        $parent_term = get_term( $parents[1], $taxonomy_name );
    }

    //term doesn't exist or error
    if ( !$parent_term || is_wp_error( $parent_term ) ) {
        return false;
    }

    return $parent_term->name;
}

Here $taxonomy_name is default to category and by default set to return top most parent. You can get the immediate parent by sending $top_most = false.

Usage Example:

//print top most parent of category id 234
echo careless_get_parent_taxonomy( 234 );


//print top most parent of WooCommerce product category id 255
echo careless_get_parent_taxonomy( 255, 'product_cat' );


//print immediate parent of category id 234
echo careless_get_parent_taxonomy( 234, 'category', false );


//print immediate parent of WooCommerce product category id 255
echo careless_get_parent_taxonomy( 255, 'product_cat', false ); 

Function code goes in the functions.php file of your active theme. And usage can be done from any template file.

This will also work for WooCommerce and any other custom taxonomy.