sitecoresitecore8sitecore-ucommerce

How to embed language in Sitecore-uCommerce nice URLs?


I am using the default configuration of uCommerce and see that uCommerce nice URLs are not language aware: http://sitename/catalogname/productname/c-XX/p-YY.

What should I do to have language in those URLs like this: http://sitename/en/catalogname/productname/c-XX/p-YY ?

Here is the configuration:

<linkManager defaultProvider="sitecore">
  <providers>
    <clear />
    <add name="sitecore" type="Sitecore.Links.LinkProvider, Sitecore.Kernel" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="always" languageLocation="filePath" lowercaseUrls="true" shortenUrls="true" useDisplayName="true" />
  </providers>
</linkManager>

Here is how I use it:

public WebshopProduct Map(UCommerceProduct uProduct)
{
    ProductCatalog catalog = CatalogLibrary.GetCatalog(25);
    IUrlService urlService = ObjectFactory.Instance.Resolve<IUrlService>();
    ...
    var url = urlService.GetUrl(catalog, uProduct) // this returns "/catalogname/productname/c-XX/p-YY"

    //And I would like to have "/en/catalogname/productname/c-XX/p-YY"
}

Solution

  • Here is what I have come up with:

    public static class TemplateIDs
    {
        // sitecore/ucommerce item's template id       
        public static ID UCommerce => new ID("{AABC1CFA-9CDB-4AE5-8257-799D84A8EE23}");
    }
    
    public static class ItemExtensions
    {
        public static bool IsUCommerceItem(this Item item)
        {
            var items = item.Axes.GetAncestors();
            return items.Any(x => x.TemplateID.Equals(TemplateIDs.UCommerce));
        }
    }
    
    public static string GetItemUrlByLanguage(Sitecore.Globalization.Language language)
    {
        if (Context.Item.IsUCommerceItem() && SiteContext.Current.CatalogContext.CurrentProduct != null && SiteContext.Current.CatalogContext.CurrentProduct.Guid == Context.Item.ID.Guid)
        {
            ProductCatalog catalog = CatalogLibrary.GetCatalog(25);
            IUrlService urlService = ObjectFactory.Instance.Resolve<IUrlService>();
            var url = "/" + language.CultureInfo.TwoLetterISOLanguageName + urlService.GetUrl(catalog, SiteContext.Current.CatalogContext.CurrentProduct);
            return url;
        }
        else
        {
            //Normal URL creation
            using (new LanguageSwitcher(language))
            {
                var options = new UrlOptions
                {
                    AlwaysIncludeServerUrl = true,
                    LanguageEmbedding = LanguageEmbedding.Always,
                    LowercaseUrls = true
                };
                var url = LinkManager.GetItemUrl(Context.Item, options);
                url = StringUtil.EnsurePostfix('/', url).ToLower();
                return url;
            }
        }
    }