Question

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.

Was it helpful?

Solution 2

You can achieve it by using:

$_product->getUrlModel()->getUrl($_product, ['_ignore_category' => true])

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top