I think, in this case, we need to create a custom event handler, which will automatically reorder the media items whenever new media is uploaded or saved.
For example:
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
public class MediaSavedEventHandler : INotificationHandler<MediaSavedNotification>
{
private readonly IMediaService _mediaService;
public MediaSavedEventHandler(IMediaService mediaService)
{
_mediaService = mediaService;
}
public void Handle(MediaSavedNotification notification)
{
foreach (var media in notification.SavedEntities)
{
if (media.ParentId > 0) // Ensure the media is inside a folder
{
var siblings = _mediaService.GetPagedChildren(media.ParentId, 0, int.MaxValue, out _)
.OrderByDescending(m => m.CreateDate); // Sort by creation date, descending
int sortOrder = 0;
foreach (var sibling in siblings)
{
if (sibling.SortOrder != sortOrder)
{
sibling.SortOrder = sortOrder;
_mediaService.Save(sibling); // Save without triggering events
}
sortOrder++;
}
}
}
}
}
Then register the event handler in the Startup.cs file or the Program.cs.
Example for registering the event handler in Program.cs
Is it possible to change so that the most recently uploaded image/document appears at the top of the Media folder in Umbraco?
Hi
When I upload a new image in Umbraco, the new image is placed at the bottom of the folder in the tree structure. Can I change how it sorts?
I know I can manually sort it in Umbraco, but I want it to be automatic when I upload images to a folder in Media.
Best regards, Josefine
Hi,
I think, in this case, we need to create a custom event handler, which will automatically reorder the media items whenever new media is uploaded or saved.
For example:
Then register the event handler in the Startup.cs file or the Program.cs.
Example for registering the event handler in Program.cs
FYI: I got the above solution from ChatGPT.
is working on a reply...