Get sitecore item relative path by item id/path

Pranay
Apr 15, 2016  ยท  16815 views

Sometimes you might need to get the relative path of a Sitecore item, say there is an item 'Sitecore/Content/Home/Categories/Products/MyProduct' which represents a page in your website with URL 'http://yoursitename/Categories/Products/MyProduct', now if you want to get the relative path i.e., '/Categories/Products/MyProduct', then this post might be for you..

Code to get item relative path/URL###

Below is the simple I have used to do the same. First get the Sitecore item path and then remove the root path and start item name from that path to get the relative path.

public static string GetItemRelativeURL(Item item)
{
    string itemPath = item.Paths.Path.ToString().ToLower();
    itemPath = itemPath.Replace(Sitecore.Context.Data.Site.RootPath.ToLower(), "");
    itemPath = itemPath.Replace(Sitecore.Context.Data.Site.StartItem.ToLower(), "");
    return itemPath;
}

Hope it helps you. Please comment if you have any suggestions.

AUTHOR

Pranay

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.


Post a comment




Thank you! You are now subscribed.

Sign up for our newsletter

Subscribe to receive updates on our latest posts.

Thank you! You are now subscribed.