Determine if Term has Grandparent/Great-Grandparent

Use get_ancestors() and count the returned array: that’s the number of ancestors a term has.

/**
 * Count a term’s ancestors.
 *
 * @param  int    $term_id
 * @param  string $taxonomy
 * @return int
 */
function wpse_57512_count_ancestors( $term_id = FALSE, $taxonomy = FALSE )
{
    if ( FALSE === $term_id and ! empty ( get_queried_object()->taxonomy ) )
    {
        $term_id  = get_queried_object_id();
        $taxonomy = get_queried_object()->taxonomy;
    }

    $ancestors = get_ancestors( $term_id, $taxonomy );

    return $ancestors ? count( $ancestors ) : 0;
}

For a practical use case you may take a look at my plugin T5 Parent Terms in body_class. Its name should tell you what it does. 🙂

Leave a Comment

error code: 523