Skip to content

Magento2 fetch store based Category URLs

I am working on a Magento site which have 3 stores:

store.default.com as default store
store.en.com as English store and
store.ae.com as Arabic store

I am trying to fetch product’s category URLs for different stores and I using following code:

public function fetchByIds($categoryIds, $storeId, $includeAnyLevel = false)
{
    if (!$categoryIds || !count($categoryIds)) {
        return [];
    }
    $categories = $this->categoryColleection->create()
     ->addAttributeToSelect('*')
     ->setStore($storeId)
     ->addAttributeToFilter('entity_id', $categoryIds);

    if ($includeAnyLevel === false) {
        $categories = $categories->addAttributeToFilter('level', ['gt' => 1]);
    }

    return $categories;
}

Note: I’ve used use MagentoCatalogModelResourceModelCategoryCollectionFactory; for $categoryColleection

Now, the Issue is I am getting unique category URL key for 3 stores but same domains as “store.default.com”. Actually I want different domains for different stores.

For that I have used below code:

$storeBasedcategory = $this->categoryRepository->get($category->getId(), $this->storeId);
$storeBasedcategory->getUrlInstance()->setScope($this->storeId);
$storeBasedcategoryUrl = $storeBasedcategory->getUrl();

It worked for me but I don’t want to fetch the category URL as passing one Id. I want to fetch them by passing an array of category Ids so that I can reduce the DB queries.

Can anyone helps me regarding the same?