In Magento 2, you can get the URL of a product using the ProductRepositoryInterface. Here’s how you can do it:
- Using ProductRepositoryInterface:
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
class YourClass
{
protected $productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->productRepository = $productRepository;
}
public function getProductUrl($sku)
{
try {
$product = $this->productRepository->get($sku);
return $product->getProductUrl();
} catch (NoSuchEntityException $e) {
// Handle exception
return null;
}
}
}
Usage:
$sku = 'your_product_sku';
$productUrl = $this->getProductUrl($sku);
Comments