Dealing with duplicate item names in Sitecore publishing

A very common challenge in Sitecore is to deal with duplicate item name inside a single parent. Many times our content authors complaint that they are not able to see latest content for an item even after publishing it many times. Let's see why users were getting older content.

What they actually do?

1. We have one item say Test under Home and published it.

On CM Server

On CD Server

2. Now, deleted the Test item, and created another item with Test name itself and published
(Or created new item named Test and deleted older one.)

On CM Server


On CD Server


Uff, how can we get latest content, when live database contains two items with same name under a single parent? Now, when you request for http://sitecoretactics/test/, it will surely going to render any random item. But due to increasing number of such cases, we thought to have a permanent solution to have unique item

Solution to have unique item on live sites

We will create a custom processor in <publishItem> pipeline that will take care for this. When the item Test gets published, it will check any other item with same name exist on target database or not. If exist with different ItemId, then it will delete that old item.

Create a PublishItemProcessor class as below.
namespace SitecoreTactics.Publishing
{
    public class RemoveDuplicateItems : PublishItemProcessor
    {
        Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
        if (sourceItem != null)
        {
            Item targetItem = context.PublishOptions.TargetDatabase.GetItem(sourceItem.Paths.Path);

            if (targetItem != null && targetItem.ID != sourceItem.ID)
            {
                context.PublishHelper.DeleteTargetItem(targetItem.ID);
            }
        }
    }
}

Using a patch config, add this processor inside pipeline as below. You may need to change processor's order if you have any customizations done in the pipeline.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <publishItem>
        <processor type="SitecoreTactics.Publishing.RemoveDuplicateItems, SitecoreTactics" />
      </publishItem>
    </pipelines>
  </sitecore>
</configuration>
Now repeat the same steps above, you will find older item gets deleted!

Comments