How to Get Product URL in Magento 2 Using ProductRepositoryInterface

In Magento 2, you can get the URL of a product using the ProductRepositoryInterface. Here’s how you can do it:

  1. 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);


Copyright © 2013-present Magesystem.net All rights reserved.