Home
Search

Start | Blogs | Episerver | Publish all descendands

2023-04-04

Episerver

How to publish all descendants in Episerver/Optimizely 11

There is no default built in functionality to mass publish pages that I could find, so I created a code solution for this:

 
   public void PublishDescendants(ContentReference parentContentReference)
{
    // Get necessary services
    var contentLoader = ServiceLocator.Current.GetInstance();
    var contentRepository = ServiceLocator.Current.GetInstance();
    // Get parent content
    var parentContent = contentLoader.Get(parentContentReference);
    // Create a writable clone of the parent content and publish it
    var clonedParentContent = parentContent.CreateWritableClone();
    contentRepository.Save(clonedParentContent, SaveAction.Publish, AccessLevel.Read);
    // Get all descendants of the parent content
    var descendantContentReferences = contentLoader.GetDescendents(parentContentReference);
    // Collect all descendants that are of type PageData in a list
    var descendantPageDataList = new List();
    foreach (var descendantContentReference in descendantContentReferences)
    {
        // Try to get the descendant content as PageData
        bool success = contentLoader.TryGet(descendantContentReference, out var descendantPageData);
        if (success)
        {
            // Add the descendant content to the list if it is of type PageData
            descendantPageDataList.Add(descendantPageData);
        }
    }
    // Publish all descendants 
    foreach (var descendantPageData in descendantPageDataList)
    {
        // Create a writable clone of the descendant content and publish it
        var clonedDescendantContent = descendantPageData.CreateWritableClone();
        contentRepository.Save(clonedDescendantContent, SaveAction.Publish, AccessLevel.Read);
    }
}

Call the method with the desired page id and all the pages below it, including itself, will be published:

    
var parent = new ContentReference(11758);
PublishDescendants(parent);