You can get the product URL by SKU in Magento 2 using ProductRepositoryInterface.
Using Magento\Catalog\Api\ProductRepositoryInterface you need to call the get($sku) method of the interface.
You can get product URL by store view level from Product URL by specific store view in Magento
If Product SKU not found, throws an error,
<?php
namespace Path\To\Class;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
class ProductUrl
{
public function __construct(
private ProductRepositoryInterface $productRepository
) {
}
/**
* This method returns the url from the product sku
*
* @return string|null
*/
public function getProductUrlBySku(): ?string
{
$sku = "24-MB01";
try {
$productUrl = $this->productRepository->get($sku)
->getProductUrl();
} catch (NoSuchEntityException $noSuchEntityException) {
$productUrl = null;
}
return $productUrl;
}
}
call $this->getProductUrlBySku(); from template or other php class.
