Finding Related Items in Sitecore

July 31, 2023

By Gorman Law

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.

Links button in Sitecore Content Editor Navigate tab

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 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;
}

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!

Gorman Headshot

Gorman Law

Full Stack Developer

Gorman is a Full Stack Developer and a University of Calgary alumni who has a background in Canada's financial industry. Outside of work, he likes to go rock climbing, try out new ice cream places, and watch sports.