I have categories with Url Rewrites Rules. For example, base url for category MyTest = /mytest. But with rewrite rule url = /new-mytest. If I use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory - I get base url (/mytest). How can I get finally url for my categiry?
2 Answers
Magento's URL rewrite engine is a great tool for improving SEO, as well as managing URLs. When you want to get the correct URL for a category based on the rewrite rules, you need to query the URL rewrite model, not just the category collection.
Here's a code snippet that shows how to get the URL by a category ID, taking into account the URL rewrites:
use Magento\UrlRewrite\Model\UrlRewrite;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite as UrlRewriteData;
use Magento\UrlRewrite\Model\UrlRewriteFactory;
use Magento\Store\Model\StoreManagerInterface;
class GetCategoryUrl
{
protected $urlRewriteFactory;
protected $storeManager;
public function __construct(
UrlRewriteFactory $urlRewriteFactory,
StoreManagerInterface $storeManager
) {
$this->urlRewriteFactory = $urlRewriteFactory;
$this->storeManager = $storeManager;
}
public function getUrlByCategoryId($categoryId)
{
$store = $this->storeManager->getStore();
$urlRewrite = $this->urlRewriteFactory->create();
$urlRewrite->loadByData([
UrlRewriteData::ENTITY_ID => $categoryId,
UrlRewriteData::ENTITY_TYPE => 'category',
UrlRewriteData::STORE_ID => $store->getId()
]);
return $urlRewrite->getRequestPath() ? $store->getBaseUrl() . $urlRewrite->getRequestPath() : false;
}
}
Here, we use the Magento\UrlRewrite\Model\UrlRewriteFactory
to create a URL rewrite object and load it by data that includes the category ID, entity type 'category', and store ID. If a rewrite exists, it returns the modified URL; otherwise, it returns false
.
Remember to instantiate your class properly and pass the category ID to the getUrlByCategoryId
method.
Make sure to clear cache and regenerate di after adding this class in your module.
-
Script return error - Invalid method Magento\UrlRewrite\Model\UrlRewrite::loadByData– WhoYouCommented Aug 14, 2023 at 10:46
Hamendra, thanks for your answer! I have adjusted your answer to my situation, because your script returns "Invalid method Magento\UrlRewrite\Model\UrlRewrite::loadByData"
Also in my case, there is no need to check the store
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite as UrlRewriteData;
use Magento\UrlRewrite\Model\UrlFinderInterface;
class GetCategoryUrl
{
protected $storeManager;
protected $urlFinder;
public function __construct (
UrlFinderInterface $urlFinder
) {
$this->urlFinder = $urlFinder;
}
public function getUrlByCategoryId($categoryId) {
$rewrite = $this->urlFinder->findOneByData([
UrlRewriteData::ENTITY_ID => $categoryId,
UrlRewriteData::ENTITY_TYPE => 'category'
]);
$targetPath = (!$rewrite) ? false : $rewrite->getRequestPath();
return $targetPath;
}
}