Sitecore Quick Tip: Programmatically Set Item to Not Publishable & Check if Is Publishable

Pretty straight forward but I needed this today. To set an entire item (not just certain versions of it) to not publishable:


using (new SecurityDisabler())
{
    item.Editing.BeginEdit();
    item.Publishing.NeverPublish = true;
    item.Editing.EndEdit();
}

Now of course this by itself will not remove the item from the content delivery servers, it needs to be published, so you can follow this up with:


Sitecore.Publishing.PublishManager.PublishItem(
    item,
    new Database[] { Database.GetDatabase("web") },
    new Language[] { Language.Parse("en") },
    false,
    true,
    false);

Which essentially says publish the item to the web database in english, do not perform a deep publish, perform a smart publish and do not publish related items.

Now more interestingly if you want to take any given item and tell whether its publishing is restricted in any way you can use the following:


var pubInfo = PublishingInformationBuilder.GetPublishingInformation(item, PublishingInformationLevel.Item);

var restrictions = pubInfo.OfType<ItemPublishingRestrictedError>().FirstOrDefault<ItemPublishingRestrictedError>();

This requires the using statements:


using Sitecore.Publishing.Explanations;
using Sitecore.Publishing.PublishingInformation;