Associate content items with a taxon

Content organization in Sitefinity CMS is entirely based on taxonomies. As shown in For developers: Flat taxonomies and For developers: Hierarchical taxonomies articles, the Tags and Hierarchical categories are implemented as taxonomies. Thus, when a content is tagged or categorized, a taxon is associated with this content. Following is an example how you can do this via code:

C#
using System;
using System.Linq;
using Telerik.Sitefinity.Modules.News;
using Telerik.Sitefinity.Taxonomies;

namespace Telerik.Sitefinity.Documentation.CodeSnippets.DevGuide.SitefinityEssentials.Taxonomies.FlatTaxonomies.FlatTaxonomyAPI
{
   public partial class FlatTaxonomyAPI
   {
       public static void AssociateNewsItemWithTaxon(Guid newsItemMasterId, string tagName)
       {
           // Get the news item
           var newsManager = NewsManager.GetManager();
           var newsItem = newsManager.GetNewsItems().SingleOrDefault(x => x.Id == newsItemMasterId);

           // Get the tag
           var taxManager = TaxonomyManager.GetManager();
           var taxon = taxManager.GetTaxa<Telerik.Sitefinity.Taxonomies.Model.FlatTaxon>().SingleOrDefault(t => t.Name == tagName);

           // Check if a tag with the same name is already added
           var tagExists = newsItem.Organizer.TaxonExists("Tags", taxon.Id);

           if (!tagExists)
           {
               // Add the tag, publish the news item and save the changes
               newsItem.Organizer.AddTaxa("Tags", taxon.Id);
               newsManager.Lifecycle.Publish(newsItem);
               newsManager.SaveChanges();
           }
       }
   }
}

In the code above, you add a tag to a news item. Take notice that every content item type has an Organizer class.

You can use a similar approach with all types of content in Sitefinity CMS.

Want to learn more?
Enhance your Sitefinity skills by enrolling in free training sessions. Become Sitefinity certified through Progress Education Community to strengthen your professional credentials.
New to Sitefinity?