Add and remove taxonomies: Remove categories

To remove a Category you need to perform the following:

  1. Use TaxonomyManager which is the manager class for taxonomies.
  2. Query the category as a HierarchicalTaxon.
  3. Call the manager’s Delete method.
  4. Call the manager’s SaveChanges method to persist the changes to the database.

Use the following code snippet:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;

namespace Telerik.Sitefinity.Documentation.CodeSnippets.DevGuide.SitefinityEssentials.Taxonomies.Tutorials
{
   public partial class TaxonomiesTutorialsSnippets
   {
       public static void RemoveCategory(string name)
       {
           var taxonomyManager = TaxonomyManager.GetManager();

           //Get the taxon

           var taxon = taxonomyManager.GetTaxa<HierarchicalTaxon>().FirstOrDefault(s => s.Title == name);

           if (taxon == null) return;

           taxonomyManager.Delete(taxon);

           taxonomyManager.SaveChanges();
       }   
   }
}

The same approach can be used with all flat and hierarchical taxonomies not only for tags and categories.
Use the following code snippet as an example where Cities is a custom Flat Taxonomy that you created:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;

namespace Telerik.Sitefinity.Documentation.CodeSnippets.DevGuide.SitefinityEssentials.Taxonomies.Tutorials
{
   public partial class TaxonomiesTutorialsSnippets
   {
       public static void AddCity(string name)
       {
           var taxonomyManager = TaxonomyManager.GetManager();

           //Get the Cities taxonomy
           var cityTaxonomy = taxonomyManager.GetTaxonomies<FlatTaxonomy>().SingleOrDefault(s => s.Name == "Cities");

           if (cityTaxonomy == null) return;

           //Create a new FlatTaxon
           var taxon = taxonomyManager.CreateTaxon<FlatTaxon>();

           //Associate the item with the flat taxonomy
           taxon.FlatTaxonomy = cityTaxonomy;

           taxon.Name = Regex.Replace(name.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

           taxon.Title = name;

           taxon.UrlName = Regex.Replace(name.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

           //Add it to the list

           cityTaxonomy.Taxa.Add(taxon);

           taxonomyManager.SaveChanges();
       }
   }
}
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?