How can I get the Canonical Product Url in list.phtml?
-
15-04-2021 - |
题
I need to get Canonical Product Url inside app/design/frontend/Vendor/Theme/Magento_Catalog/templates/product/list.phtml
.
I tried to use:
$block->getProductUrl($_product)
and:
$_product->getUrl()
but I receive the product url with all the categories while the canonical url has no category. I'm using the Mageworx SEO extension if this can help.
解决方案 2
You can achieve it by using:
$_product->getUrlModel()->getUrl($_product, ['_ignore_category' => true])
其他提示
You need to inject this below class in your construct :
private $productRepository;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
){
$this->productRepository = $productRepository;
}
After that, you can add this below line to get canonical url :
$product = $this->productRepository->getById(1); //pass your product id
echo $product->getUrlInStore();
Remove generated and check it.