Tuesday, November 24, 2015

Basics: How to publish an item programmatically to all targets in Sitecore

Here's a tidbit that I found myself googling about and I couldn't find an answer to.. How to publish an item to all available publishing targets.

I needed to do this to avoid hard-coding database names when publishing programmatically. So I went in to see how Sitecore does it from the ribbon command (Sitecore.Shell.Framework.Commands.PublishNow)

After some digging around in the Kernel, I ended up with something along these lines:

 Database contextDatabase = Sitecore.Context.Database;  
 Item itemToPublish = contextDatabase.GetItem("/sitecore/content/home"); //some item that needs to be published  
 //get all the available targets  
 List<Database> databases = new List<Database>();  
 ItemList targets = PublishManager.GetPublishingTargets(contextDatabase);  
 foreach (Item targetItem in targets)  
  Database database = Factory.GetDatabase(targetItem[FieldIDs.PublishingTargetDatabase]);  
   if (database != null)  
 List<Language> languages = new List<Language>();  
 //invoking the static PublishManager.PublishItem  
 PublishManager.PublishItem(itemToPublish, databases.ToArray(), languages.ToArray(), false, true);  

If working within the Sitecore Client, you will want to use Sitecore.Context.ContentDatabase instead of Sitecore.Context.Database

Also, if you want to publish in all languages, you can use LanguageManager.GetLanguages(contextDatabase) instead.