Welcome! This blog aims to teach you how to find related items in Sitecore inside the Content Editor, C# code, and PowerShell.
While in the Content Editor, click on the Navigate tab on the top, then click on Links in the ribbon.
Simple as that!
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 item links
ItemLink[] itemLinks = Globals.LinkDatabase.GetReferrers(item);
//exit if there are no
if (itemLinks == null || itemLinks.Length == 0)
{
return;
}
//loop through list
foreach (ItemLink itemLink in itemLinks)
{
//get database. Can use master as well
Database db = Factory.GetDatabase("web");
//get item by ID
Item linkItem = db.GetItem(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;
}
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} }
That’s all! I hope this blog was helpful in showing you the different ways to get referred items in Sitecore!
Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.