Created
July 4, 2022 03:05
-
-
Save phamngsinh/ba9d5e8da4e8d3b90894dc7f2a5ab333 to your computer and use it in GitHub Desktop.
Get Product URL for Specific Store in Magento 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment