1

I have a 2 website.

  1. https://website.com (Default Website)
  2. https://site.website.com (Secondary Website)

Now I'm accessing the admin panel using the https://website.com/admin/catalog/category... Now when I save the categories I have an observer that generate the menu for each of this site. Take note that each website is using different root category. Upon clicking the save category button it generate an html file which contains the list of categories for each website. But the problem now is when I checked the generated url for https://site.website.com/ it generates a category url of https://website.com/secondsitecategory which I expect should be https://site.website.com/secondsitecategory.

Below is my code to retrieve the category in Magento 2

$subcategories = $category->getCollection()
            ->addAttributeToSelect('*')
            ->setStoreId($store->getId())
            ->addAttributeToSort('position', 'ASC')
            ->addIdFilter($category->getChildren())
            ->load();

Note: the $category in $category->collection() is the root category of every website. I tried using emulator like

$this->_emulator->startEnvironmentEmulation($store->getId(), \Magento\Framework\App\Area::AREA_FRONTEND, true);

before every $category->getCollection() but it's not working. Would any one of you have an idea on how to solve this?

0

Use below code to set store before loading collection.

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/

protected $_storeManager;

public function __construct(
 \Magento\Store\Model\StoreManagerInterface $storeManager
) {
  $this->_storeManager = $storeManager;
}

now you can set your current store like

$this->_storeManager->setCurrentStore('YOUR_STORE_ID');
|improve this answer|||||
  • This don't work. Tried it and it's still returning the main website url and not the url of the expected store for the secondary website – MadzQuestioning Mar 3 '19 at 12:32
0

You have to add joinUrlRewrite() to collection for getting the store repective URL

    $subcategories = $category->getCollection()
        ->addAttributeToSelect('*')
        ->setStoreId($store->getId())
        ->addAttributeToSort('position', 'ASC')
        ->addIdFilter($category->getChildren())
        ->joinUrlRewrite() // add This
        ->load();
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.