How to Get Product URL for Specific Store in Magento 2
Medium to large-sized Magento 2 stores tend to use the multi-store facility.
If a merchant wants to sell the same products in the USA and in the UK, he/she would use multi-store for separating the store and product URL.
As the number of stores increases, it becomes difficult for the admin to get store wise product URL in Magento 2.
This tutorial explains how to get product URL for specific store in Magento 2.
You can use the solution while migrating to latest Magento 2 version or developing custom functionalities for which you need to get the products URL.
Solution to Get Product URL for Specific Store in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace Meetanshi\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]); } } |
Need further help regarding this solution? Feel free to ask in the Comments section below.
I would be glad to solve your queries.
Do consider sharing this post with Magento Community via social media.
Thank you.
Related Post: How to Get Product Image URL in Magento 2
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Add Product Attribute to Sales Rules Conditions in Magento 2
Solved: PHP Fatal Error Class ‘locale’ Not Found in Magento 2
Next