I need to load a product using its URL key. I find methods to load using only ID and SKU like,

use Magento\Catalog\Model\ProductRepository;

$product = $this->_productRepository->getById($productId);
$product = $this->_productRepository->get($productSku);

How can I achieve this using URL key?


You can use the product collection:

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;


$collection = $this->productCollectionFactory->create();
           ->addAttributeToFilter('url_key', $yourUrlKey);
$product = $collection->getFirstItem();

Another option is to use the UrlRewrite collection (Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory) to fetch the line from url_rewrite table with request_path = $yourUrlKey and entity_type='product'. There, you will find the desired entity_id of the product and you can simply load it.

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.