How to Find Related Items in Sitecore
Welcome! This blog aims to teach you how to find related items in Sitecore inside the Content Editor, C# code, and PowerShell.
1. Content Editor
While in the Content Editor, click on the Navigate tab on the top, then click on Links in the ribbon.
Simple as that!
2. C# Code
The code is below! Read the comments for more information.
//include these
using Sitecore.Links;
using Sitecore.Data.Items;
//function returns list of Item
public List<Item> GetReferreredItems()
{
List<Item> referredItems = new List<Item>();
//get current item
Item item = Sitecore.Context.Item ;
//create list of related <span class="hljs-keyword">item </span>links
<span class="hljs-keyword">ItemLink[] </span><span class="hljs-keyword">itemLinks </span>= Globals.LinkDatabase.GetReferrers(<span class="hljs-keyword">item);
//exit if there are no
if (itemLinks == null || itemLinks.Length == 0)
{
return;
}
//loop through list
foreach (<span class="hljs-keyword">ItemLink </span><span class="hljs-keyword">itemLink </span>in <span class="hljs-keyword">itemLinks)
{
//get database. Can use master as well
Database db = Factory.GetDatabase("web");
//<span class="hljs-meta">get</span> <span class="hljs-keyword">item </span><span class="hljs-keyword">by </span>ID
<span class="hljs-keyword">Item </span>linkItem = db.GetItem(<span class="hljs-keyword">itemLink.SourceItemID);
//if item is not null
if (linkItem != null)
{
//add to list
referredItems.add(linkItem);
//room to do other stuff to related item
}
}
//return list
return referredItems;
}
3. PowerShell
If you have Sitecore PowerShell installed, you can get related items here too! The code is below, read the comments for more details:
#display stuff
$props = @{
InfoTitle = "Referred items tutorial!"
InfoDescription = "Lists all items that are using this item"
}
#function that returns list of referred items
function Get-ReferreredItems {
#get desired item.
$item = Get-Item -Path "enter path your desired item here"
#get database
$db = [Sitecore.Globals]::LinkDatabase
#get list of referred items
$itemLinks = $db.GetReferrers($item)
#loop list
foreach($itemLink in $itemLinks){
#get item from linked ID
$linkItem = Get-Item -Path master:\ -ID $itemLink.SourceItemID
$linkItem
}
}
#call function
$items = Get-ReferreredItems
#display names and paths of referred items
$items | Show-ListView @props -Property @{Label="Name"; Expression={$.DisplayName} }, @{Label="Path"; Expression={$.ItemPath} }
Conclusion
Thatโs all! I hope this blog was helpful in showing you the different ways to get referred items in Sitecore!