Custom sorting of Terms in TermSet using PowerShell
Many time we come across scenarios where we need to sort the terms of any term set or terms within term in the order other then the custom out of box sorting.
This can be achieved very easily using out of box sort order provided. For doing the sorting manually, we can navigate to Term Store Management screen, select the term or term set whose terms need to be sorted. On the right side of screen, select the custom sort tab. click on custom sort radio button. All the term would appear with a drop down next to them. Drop next to them will have there custom sort order, enter the appropriate sort order and click on save.
If we need to make chages in more than one environment, making changes manually in all the environment would be tedious. For that we can write the PowerShell script and all we need to do is run the PowerShell script in each environment.
For Setting the sort order using power shell, we need to use the CustomSortOrder property of termSet or term.
CustomSortOrder takes the Guid of terms to be sorted , separated by " : ". For example if my TermSet has 4 terms Term1 , Term2 , Term3 and Term4. and we want to sort the terms like Term2 , Term3 , Term1, Term4. All we need to do is set the CustomSortOrder property of termSet to Guid_of_Term_2:Guid_of_Term_3:Guid_of_Term_1:Guid_of_Term_4 and call commitAll() on term store. That's it.
$taxonomySession = Get-SPTaxonomySession -Site "Your Site Path"
$termStore = $taxonomySession.TermStores["Your Term Store Name"]
if($termStore -ne $null)
{
$group = $termStore.Groups["Your Group Name"]
if($group -ne $null)
{
$termSet = $group.TermSets["Your Term Set Name"]
foreach($term in $termSet.Terms)
{
switch ($term.Name)
{
"Term2" { $term1 = $term.ID.ToString() + ":" }
"Term3" { $term2 = $term.ID.ToString() + ":" }
"Term1" { $term3 = $term.ID.ToString() + ":" }
"Term4" { $term4 = $term.ID.ToString() }
}
}
$customSortOrder = $term1 + $term2 + $term3 + $term4;
$termSet.CustomSortOrder = $customSortOrder
}
}
$termStore.CommitAll();
Comments
- Anonymous
May 20, 2011
Hey Kaushal very nice details