This post gives a detailed example of a Sitecore PowerShell script that automates the process of inserting content components (renderings) with particular content into a number of items.
Recently a client of ours wanted to roll out a promotion content row to all items of a particular template.
- These items also happened to be bucket items so there were quite a few of them.
- The components were usually added to the page via the Experience Editor.
- The components were used in a building blocks manner:
- Add a full-width Row
- Add a Two column component inside the row
- Add an image in the left-hand column
- Add a rich text component in the right-hand column
- The components were added via Dynamic Placeholders.
You could achieve this in certain cases by adding to the Standard Values however if your items already vary drastically from the Standard Values you may not get good enough coverage.
So here is the script with lots of comments so that you can follow along.
View the full script in our GitHub Repo here.
Key Take Aways
- We found you need to use Add-Rendering and then Get-Rendering in order to get the correct UniqueID of the rendering just added.
- In order to construct the Dynamic Placeholder name correctly, you will need the correct UniqueID of the parent just added to the page.
- The easiest way to facilitate that lookup in Get-Rendering was to give the rendering a unique parameter to identify it.
- Without this, you may get a list of all renderings that match the non-specific lookup you just used in Get-Rendering
- Because of the way Dynamic Placeholders are added to the page this worked best in the Final Layout.
- If things go really wrong in your script its best practice to spin up a new Item Version so that you can roll these changes back via another script.
Add-ItemVersion -Path $i.Paths.Path -IfExist Append -Language "en"
- If you have two dynamic placeholders with the same base name then an additional postfix is used to target the second one. So for instance in our case, we had a left and a right-hand column with dynamic placeholders that use the same base placeholder name. In order to target the right-hand side you use “_1” on the end:
$colWidePlaceholderRight = "/page-body-meeting/row_$rowId/col-wide_$($twoColumnRenderingId)_1"
- Nested Dynamic Placeholders: The line of code in point for above also shows how to construct the placeholder key of a nested dynamic placeholder. In this case, we have a Column inside a Row. The PowerShell script you use to build your components needs to keep track of the placeholder hierarchy so that you can continue to construct nested dynamic placeholders.