Stack Exchange
Get Storefront Product URL for Magento 2
I am trying to get the storefront product URL.
$_Product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
echo $_Product->getUrlModel()->getUrl($_Product);
For some of the products, the URL is showing as the product admin url. i.e., http://example.com/admin/catalog/product/view/id/463/s/product-name/key/21e3132388ab54cb00eb98bd047bb535057a7e9e44efac8b79cfe599e7ec7bad/
I want the product URL as http://example.com/product-name.html

<?php
namespace Name\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Api\ProductRepositoryInterface;

class Data extends AbstractHelper
{
    protected $productModel;
    protected $productRepository;

    public function __construct(
        Context $context,
        Product $productModel,
        ProductRepositoryInterface $productRepository
    )
    {
        $this->productModel = $productModel;
        $this->productRepository = $productRepository;
        parent::__construct($context);
    }

    public function getProductUrl($productId, $storeId)
    {
        $product = $this->productModel->load($productId);
        $product->setStoreId($storeId);
        $url = $product->getProductUrl();
        // another way to get url
        $product = $this->productRepository->getById($productId, false, $storeId);
        $productURL = $product->setStoreId($storeId)->getUrlModel()->getUrlInStore($product, ['_escape' => true]);
    }
}


Try with below code
$_Product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId()); 
echo $_Product->getProductUrl();

Note : Don't use objectmanager directly in your .phtml instead use block or helper to load the product.

Tried that one as well. Still not working.

Try loading product using Repository, Thanks!

Try to using this
    $productId = 1;

    $productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
    $product = $productRepository->getById($productId);
    $product->getProductUrl();

It just an example don't use objectManager directly you can inject the class Magento\Catalog\Api\ProductRepositoryInterface to constructor

Still not working.

try to print/log all product data like $product->getData() and check url is there

$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$productBD = $productRepository->getById(your_product_id);
$productBD->getProductUrl()

in case you don't have your product ID you can get it by SKU using this:
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$productID=$productRepository->getIdBySku($sku);

Make sure you are calling this in the context of a store view in wich your product exists !
