简体   繁体   中英

Unpublish sitecore item programmatically

I know it's possible to publish item from code level with Sitecore.Publishing.PublishManager . I don't see there option to unpublish an item.

Is it possible in some way?

You need to set value of __Never publish field to 1 (which is how Sitecore stores true boolean value) and publish the item.

Yes, it's publishing, but because value of __Never publish is set to true, Sitecore will remove the item from the web database.

You can also set value of this field by using item.Publishing.NeverPublish property.

Something like this should do the trick:

item.Editing.BeginEdit();
item.Publishing.NeverPublish = true;
item.Editing.EndEdit();

PublishManager.PublishItem(item, targets, item.Languages, false, false);

Not in a workflow

Items marked as NeverPublish will be unpublished during publishing. Since NeverPublish is a shared field all versions will be unpublished.

bool originalNeverPublish = item.Publishing.NeverPublish;

item.Editing.BeginEdit();
item.Publishing.NeverPublish = true;
item.Editing.EndEdit();

PublishManager.PublishItem(item, targets, item.Languages, false, false);

item.Editing.BeginEdit();
item.Publishing.NeverPublish = originalNeverPublish;
item.Editing.EndEdit();

In a workflow

If the item is in a workflow, publishing will publish all versions of the item that is in a Final / IsApproved state, ignoring the value of NeverPublish . We should instead change the workflow state of the versions we want to unpublish.

In the example below I assume that the initial state isn't marked as Final / IsApproved .

var workflowProvider = item.Database.WorkflowProvider;
var workflow = workflowProvider.GetWorkflow(item);

foreach (var version in item.Versions.GetVersions())
{
    if (workflow.IsApproved(version))
    {
        workflow.Start(version);
    }
}

PublishManager.PublishItem(item, targets, item.Languages, false, false);

Publishing an item simply moves it to Web database.

Just remove your item from that database to unpublish it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM