Cleaning up orphaned
renderings in Sitecore
, especially when content editors remove parent components without also removing child renderings, can be a challenging task. This is particularly true when dealing with both static and dynamic placeholders
. Here’s a PowerShell script
that you can use to find and clean up orphaned renderings
on a Sitecore page.
Here's a PowerShell
script to get you started:
# Define the root path of the pages where orphaned renderings need to be cleaned up
$rootPath = "/sitecore/content/Home"
# Get the root item
$rootItem = Get-Item -Path $rootPath
# Function to find and remove orphaned renderings
function Remove-OrphanedRenderings {
param (
[Sitecore.Data.Items.Item]$item
)
# Get all renderings (static and dynamic)
$renderings = @()
$placeholders = $item.Visualization.Renderings
foreach ($placeholder in $placeholders) {
foreach ($rendering in $placeholder) {
$renderings += $rendering
}
}
# Process each rendering
foreach ($rendering in $renderings) {
$componentItem = Get-Item -Path $rendering.DataSource
if ($componentItem -eq $null -or -not $componentItem.Exists) {
# If the parent component does not exist, remove the rendering
Write-Host "Orphaned rendering found: $($rendering.Id) at $($item.Paths.FullPath)"
Remove-Rendering -Item $item -Rendering $rendering
}
}
}
# Function to remove a specific rendering
function Remove-Rendering {
param (
[Sitecore.Data.Items.Item]$item,
[Sitecore.Mvc.Presentation.Rendering]$rendering
)
# Find and remove the rendering from the item
$placeholder = $item.Visualization.Renderings | Where-Object { $_.Contains($rendering) }
if ($placeholder) {
$placeholder.Remove($rendering)
Write-Host "Removed rendering $($rendering.Id) from $($item.Paths.FullPath)"
}
}
# Recursively process items under the root item
$itemsToProcess = Get-Item -Path $rootPath -Recurse
foreach ($item in $itemsToProcess) {
Remove-OrphanedRenderings -item $item
}
Write-Host "Orphaned rendering cleanup completed."
If you have specific requirements or additional complexities (like custom placeholder types or specific rendering setups), you might need to further adjust the script accordingly.