Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save phamngsinh/ba9d5e8da4e8d3b90894dc7f2a5ab333 to your computer and use it in GitHub Desktop.

Select an option

Save phamngsinh/ba9d5e8da4e8d3b90894dc7f2a5ab333 to your computer and use it in GitHub Desktop.
Get Product URL for Specific Store in Magento 2
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