Get Taxonomy Terms by Alias

Taxonomies are a way of adding a category or tags to a content item. The tags and categories of a taxonoy are called Terms. Getting the Terms of a taxonomy by alias is not very obvious. They are not root content items that you can access via the IContentManager interface. This requires some custom logic by iterating through the Terms of a Taxonomy ContentPart.

First lets get the ContentItemId of the Taxonomy content item.

    // retrieve the ContentItemId matching the taxonomy alias by using the IContentAliasManager
    var contentItemId = await _contentAliasManager.GetContentItemIdAsync($"alias:{taxonomyAlias.ToLowerInvariant()}");
    if (string.IsNullOrWhiteSpace(contentItemId))
    {
        // no content item was found matching the alias.
        return;
    }

Now we have the id we can get the ContentItem of the Taxonomy and access it as TaxonomyPart.

    // get the published ContentItem by using the IContentManager
    var taxonomyContentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);
    var taxonomyPart = taxonomyContentItem.As<TaxonomyPart>();

Finally we have a collection of Terms through which we can iterate. This method is part of a method that returns an IEnumerable<string>. We yield return all content item ids that match the alias.

    foreach (var termContentItem in taxonomyPart.Terms)
    {
        // check the term name against the alias
        var aliasPart = termContentItem.As<AliasPart>();
        if (!string.IsNullOrWhiteSpace(aliasPart?.Alias) &&
            aliasPart.Alias.Equals(termName, StringComparison.CurrentCultureIgnoreCase))
        {
            yield return termContentItem.ContentItemId;
        }
        // check the term name against the display text
        else if (termContentItem.DisplayText.Equals(termName, StringComparison.CurrentCultureIgnoreCase))
        {
            yield return termContentItem.ContentItemId;
        }

        // a Term can have a child collection of terms as well
        if (!(termContentItem.Content.Terms is JArray childTermJArray))
        {
            // no child terms found.
            continue;
        }

        var childTerms = childTermJArray.ToObject<IEnumerable<ContentItem>>();
        foreach (var childTermContentItemId in GetChildTermsContentItemId(childTerms, termName))
        {
            yield return childTermContentItemId;
        }
    }