Create a custom sorting routine for content

How to Implement a Custom Child Sorting Rule

Sitecore provides a number of out-of-the-box sorting rules that can be implemented throughout your solution. Some of these include:

  • Created By
  • Display Name
  • Logical
  • Reverse
  • Updated

If you need to apply your own custom logic to child items, Sitecore enables developers to quickly build custom sorting rules.

  1. Create a custom comparer source code file using Sitecore Rocks
    1. New Item... >> Sitecore > UI > Subitems Sorting Comparer
    2. Modify to meet your sorting requirements
  2. Examples code below sorts based on common "Title" field
    1. namespace Sitecore.Starterkit
    2. {
    3. using Sitecore.Data.Comparers;
    4. using Sitecore.Data.Items;
    5. public class TitleComparer : Comparer
    6. {
    7. protected override int DoCompare(Item item1, Item item2)
    8. {
    9. string title1 = item1["Title"];
    10. string title2 = item2["Title"];
    11. if ((title1.Length > 0) && (title2.Length > 0))
    12. {
    13. if ((title1[0] == '_') && (title2[0] != '_'))
    14. {
    15. return 1;
    16. }
    17. if ((title2[0] == '_') && (title1[0] != '_'))
    18. {
    19. return -1;
    20. }
    21. }
    22. return title1.CompareTo(title2);
    23. }
    24. }
    25. }
  3. In the Content Editor, select the /Sitecore/System/Settings/Subitems Sorting item
  4. In the Content Editor, insert a child sorting rule definition item using the /System/Child Sorting data template. For the name of the item, use the name of the custom item comparer class or the name of the property by which the custom item comparer sorts
  5. In the Content Editor, select the newly created child sorting rule definition item
  6. In the Content Editor, in the new child sorting rule definition item, in the Data section, in the Type field, enter the signature of the custom item comparer class. See example below from a project called Starterkit.
    setting
  7. Save your changes and you'll be ready to test and use your new Sorting Rule
  8. To implement, select and item of which child items you want to sort using your sorting rule. If you haven't done so already, show Standard Fields (View tab >> Standard Fields). Go to the Appearance field section and select your custom sorting rule in the Child Sorting rule field.

    NOTE: Keep in mind that the Sortorder field (In Appearance field section) is going to overrule any child sorting rules. Set values to null for child sorting to take effect.