Add and remove taxonomies: Add categories
To add a new category you will need to perform the following:
- Use
TaxonomyManagerwhich is the manager class for Taxonomies. - Get the
Categoriestaxonomy object. - Create a new
Taxonof typeHierarchicalTaxon. - Assign the
Categoriestaxonomy to the taxon item that you created. - If you want to assign a parent for the taxon, use the
Parentproperty. - Add the
Taxonto theCategorytaxonomy - Call the manager’s
SaveChangesmethod to persist the changes to the database.
Use the following code sample:
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 AddCategory(string name, HierarchicalTaxon parentCategory)
{
var taxonomyManager = TaxonomyManager.GetManager();
//Get the Categories taxonomy
var categoryTaxonomy = taxonomyManager.GetTaxonomies<HierarchicalTaxonomy>().SingleOrDefault(s => s.Name == "Categories");
if (categoryTaxonomy == null) return;
//Create a new HierarchicalTaxon
var taxon = taxonomyManager.CreateTaxon<HierarchicalTaxon>();
//Associate the item with the hierarchical taxonomy
taxon.Taxonomy = categoryTaxonomy;
taxon.Name = Regex.Replace(name.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
taxon.Title = name;
taxon.UrlName = Regex.Replace(name.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
//Check if the parent has been set
if (parentCategory != null)
{
taxon.Parent = parentCategory;
}
//Add it to the list
categoryTaxonomy.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.
Get started with Integration Hub | Sitefinity Cloud
This free lesson teaches administrators, marketers, and other business professionals how to use Sitefinity Integration Hub to create automated workflows between Sitefinity and other business systems.
Web Security for Sitefinity Administrators
This free lesson teaches administrators the basics about protecting your Sitefinity instance and your sites from external threats. Configure HTTPS, SSL, allow lists for trusted sites, and cookie security, among others.
Foundations of Sitefinity ASP.NET Core Development
The free on-demand video course teaches developers how to use Sitefinity ASP.NET Core and take advantage of its decoupled architecture and modern development model.