Magento – Magento 2 Get Product Url For Specific Store

elasticsearchmagento-2.1.8product-urls

I have multi stores enabled in my Magento instance. I am trying to get product url for each store as I need to index data in Elasticsearch.

What I have tried but not getting the result with store appended in url.

$productId = 2;
$storeId = 4;
$product = $this->productRepository->getById($productId, false, $storeId);
$product->setStoreId($storeId)->getUrlModel()->getUrlInStore($product, ['_escape' => true]);

I expect result as

http://example.com/mystorecode/product1.html

Where as I get the result

http://example.com/product1.html

Best Answer

From the Magento2 root, you can run below code inside any custom php file.

require './app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$_objectManager = $bootstrap->getObjectManager();
$state = $_objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('admin');
$registry = $_objectManager->get('Magento\Framework\Registry');
$registry->register('isSecureArea', true);

$productId = 184294;
$storeId = 27;
$product = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productId, false, $storeId);
echo $product->setStoreId($storeId)->getUrlModel()->getUrlInStore($product, ['_escape' => true]);