Extension method to get Sitecore start item or home item from any itemId on Sitecore multi-site environment

5/21/2018 extension-method sitecore-multisite

Extension method to get Sitecore start item or home item from any itemId on Sitecore multi-site environment

When we are in website context it's easy to get context item like below: 

var currentItem = Sitecore.Context.Item;

  

When you are in website context it's easy enough to get Home item on the site as below: 

var currentSiteHomeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);

 

When you are not in website context, its bit tricky to get HomeItem based on Item id or path of the item. We can get this kind of scenario when we are in Sitecore shell site context and have Sitecore multiple sites.  But still, it's possible, below are the extension methods I have written for an item.

public static Item GetSiteStartItem(this Item contextItem)
{
	return contextItem?.Database.GetItem(contextItem.GetSiteStartItemPath(), Context.Language);
}

public static string GetSiteStartItemPath(this Item item)
{
	var siteConfig = item.GetSiteInfo();
	if (siteConfig != null)	
        {
		var rootPath = siteConfig.RootPath;
		var startItemPath = siteConfig.StartItem;
		return string.Concat(rootPath, startItemPath);
        }     
return null;
}
public static SiteInfo GetSiteInfo(this Item item)
{
	var siteInfoList = Factory.GetSiteInfoList();
	SiteInfo currentSiteinfo = null;
	var matchLength = 0;
	foreach (var siteInfo in siteInfoList)	{
		if (!item.Paths.FullPath.StartsWith(siteInfo.RootPath,
 StringComparison.OrdinalIgnoreCase) ||			siteInfo.RootPath.Length <= matchLength) continue;
		matchLength = siteInfo.RootPath.Length;
		currentSiteinfo = siteInfo;
	}
	return currentSiteinfo;
}

Hope this helps someone!