We have lot of items in the one of the image folder so we are planning to move these images in multiple folder. We would like to do this programmatically however we are not sure if it will impact the field it is used in Items or not? We want to update all the reference link also along with movement of the media. Can it be possible?
3 Answers
If you are using media items in image field or rich text, then you do not need to change anything because when any item move it does not change item guid it remains same.
As others have mentioned Sitecore stores the Id of the Media item in the field value so you should be able to move it without having any impact.
One of the best and easiest ways to do this is to use SPE.
I've written about bulk moving items here before: https://www.flux-digital.com/blog/bulk-move-items-sitecore-powershell-extensions
I've written an example script which will go through your images and move them to an sub-folder using year-month format (e.g "2019-09"):
#Moves Images to sub-folders with year-month format (e.g "2019-09") to organise them better and improve performance
$imageRootPath = "master:/sitecore/media library/My Site/Images/"
$images = Get-ChildItem -Path $imageRootPath
foreach ($image in $images) {
#get year-month folder format and create folder path
$monthFolderName = [datetime]$image.Created
$subFolderPath = "$($imageRootPath)/$($monthFolderName.ToString('yyyy-MM'))"
#if a year-month folder already exists then move the image to this folder
if (Test-Path $subFolderPath) {
Write-Host "Sub-folder Exists, moving image to: $($subFolderPath)";
Move-Item -Path $image.ItemPath -Destination $subFolderPath;
}
#if a year-month folder doesn't exists then create it and move the image to this folder
else {
Write-Host "Sub-folder Doesn't exist, creating sub-folder: $($subFolderPath)";
New-Item -Path $subFolderPath -Name "" -ItemType "/sitecore/templates/System/Media/Media folder"
Write-Host "Moving image to: $($subFolderPath)";
Move-Item -Path $image.ItemPath -Destination $subFolderPath;
}
}
Once you've run this the structure will look something like so:
You could always update this script to use a different format such as a-z or year only etc depending on what you would prefer.
By Default Sitecore uses Media Id to store the image/media reference in a field. for example -
<image mediaid="{DB854E88-4293-4D0B-9623-85F58FCAB7D6}" />
You can see this in the raw value of the image field, same is for the RTE field but if you are using the media path for specific item somewhere in the code, then you need to update your code in this case. If you are only worried about the Sitecore fields then you are good to go, the movement of media item will not change the media item ids.
-
At this point i am worried about Sitecore fields. I believe that if it is used in code (ideally it should not be) then i need to make code changes for it. Thanks for your reply. Commented Sep 9, 2019 at 10:42