July 21, 2024

Get child taxa of parent taxon in Sitefinity

Taxonomies are a powerful feature in content management systems like Sitefinity, allowing you to categorize and manage content effectively. In this post, we’ll explore a piece of code that dynamically fetches and displays hierarchical taxonomies related to events, specifically the “Related Event Series” taxonomy.

The Code

@using Telerik.Sitefinity.Taxonomies.Model; 
@using Telerik.OpenAccess; 
@using Telerik.Sitefinity.Taxonomies;

// Parent Taxon name example: Related Event Series

Dictionary<Guid, string> relatedEventSeriesTaxonomyIds = new Dictionary<Guid, string>();
TaxonomyManager taxMan = TaxonomyManager.GetManager();
HierarchicalTaxon relatedEventSeriesTaxons = taxMan.GetTaxonomy<HierarchicalTaxonomy>(TaxonomyManager.CategoriesTaxonomyId).Taxa.Cast<HierarchicalTaxon>().FirstOrDefault(t => t.Title.Equals("Related Event Series"));
if (null != relatedEventSeriesTaxons) {
    foreach (var taxa in relatedEventSeriesTaxons.Subtaxa) {
        if (!relatedEventSeriesTaxonomyIds.ContainsKey(taxa.Id)) {
            relatedEventSeriesTaxonomyIds.Add(taxa.Id, taxa.Title);
        }
    }
}
@if (item.TaxonomyIds != null) {
    var taxons = relatedEventSeriesTaxonomyIds.Where(a => item.TaxonomyIds.Any(b => b == a.Key.ToString())); 
    if (taxons != null) {
        <div>
            <span class="screenreaders-only">Type:</span>
            @foreach (var taxon in taxons) {
                <span class="title-pill">
                    <span>@taxon.Value</span>
                </span>
            }
        </div>
    }
}

How It Works

  1. Using Directives: The code starts by including necessary namespaces for working with taxonomies and OpenAccess in Sitefinity.
  2. Initialize Taxonomy Dictionary: A dictionary is created to store taxonomy IDs and their corresponding titles.
  3. Fetch Taxonomy Manager: The TaxonomyManager is used to fetch taxonomies.
  4. Get Specific Taxonomy: The code retrieves the “Related Event Series” taxonomy and its subtaxonomies.
  5. Display Related Taxonomies: If the item has taxonomy IDs, the code filters and displays the matching taxonomies.

Using the Code

To use this code, you need to integrate it into your Sitefinity project’s Razor view. This code snippet dynamically generates a list of related event series taxonomies for a given item and displays them in a user-friendly format.

Conclusion

This code demonstrates how to work with hierarchical taxonomies in Sitefinity, providing a method to fetch and display related event series taxonomies dynamically. By understanding and utilizing these techniques, you can create more organized and easily navigable content structures on your website.