Sitecore manual publish an item in all publishing targets and languages

5/21/2018 sitecore-publish

Sometimes we need to trigger Sitecore publish on an item on all publishing targets and on all languages. Here is the way we can achieve it.

To get all publishing target database names:


var publishingTargetDatabaseNames = Sitecore.Publishing.PublishManager.GetPublishingTargets(
                                    Sitecore.Configuration.Factory.GetDatabase("master"))
                                    .Select(x => x["Target database"]).ToArray();

To get all languages for the master database:

var publishingTargetLanguages = Sitecore.Configuration.Factory.GetDatabase("master").Languages;

 

To trigger a manual publish in Sitecore:


Sitecore.Publishing.PublishManager.PublishItem(itemsToPublish.FirstOrDefault(),	publishingTargetDatabaseNames.Select(Sitecore.Configuration.Factory.GetDatabase).ToArray(),
	publishingTargetLanguages,
	deep: true,
	compareRevisions: true, //Do smart publish for the item	publishRelatedItems: true);

To clear Sitecore cache manually:

 Sitecore.Caching.CacheManager.ClearAllCaches();

Adding all together in item publish event: 

 

var publishingTargetDatabaseNames = Sitecore.Publishing.PublishManager.GetPublishingTargets(
                                    Sitecore.Configuration.Factory.GetDatabase("master"))
                                    .Select(x => x["Target database"]).ToArray();
var publishingTargetLanguages = Sitecore.Configuration.Factory.GetDatabase("master").Languages;Sitecore.Publishing.PublishManager.PublishItem(itemsToPublish.FirstOrDefault(),
												publishingTargetDatabaseNames.Select(Sitecore.Configuration.Factory.GetDatabase).ToArray(),
												publishingTargetLanguages,
												deep: true,
												compareRevisions: true, //Do smart publish for the item
												publishRelatedItems: true);
//Clear cache manuallySitecore.Caching.CacheManager.ClearAllCaches();

 

Deep: this parameter specifies whether to include subitems or not. If you only want to publish item go for false.

Compare Revisions: this parameter specifies if this publish is smart publish or republish. Go for true if u want smart publish. Going for republishing is necessary sometimes due to media items but keep an eye on performance.

publishingTargetDatabases is an array of databases.