Unpublish sitecore item programmatically
Asked Answered
B

3

6

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?

Brenza answered 6/7, 2016 at 8:57 Comment(0)
M
12

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);
Marshamarshal answered 6/7, 2016 at 9:14 Comment(0)
A
0

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);
Abilene answered 21/6, 2017 at 21:35 Comment(0)
B
-4

Publishing an item simply moves it to Web database.

Just remove your item from that database to unpublish it.

Braw answered 6/7, 2016 at 9:0 Comment(1)
This isn't helpful and should be considered bad practice. Many Sitecore solutions have multiple web databases, especially in distributed environments. Further to this the web databases should not be modified directly. @Marek Musielak has explained the correct way of doing this.Beckerman

© 2022 - 2024 — McMap. All rights reserved.