'Getting product page moved to new link prestashop 1.7

I am trying to get the link of the product pages in prestashop. After going through the product class I found the function getLink() and using that I get a link but when I try to go to that link I get an error that page moved to a new link. How to solve this? Following below are the statements I am using to get the links.

  $product = new Product(4);
  $link = $product->getLink();


Solution 1:[1]

I had to do this to get it to work with Prestashop 1.7:

$identifier = $product['id_product'] . '-' . $product['id_product_attribute'];
$url = $this->context->link->getProductLink($identifier);`

I checked the getProductLink() method in the Link class and found that it doesn't actually add the attribute id by its self.

Solution 2:[2]

On prestashop 1.7.x :

$product = new ProductCore($value['id_product']);
echo $product->getLink() . '<br>';

Solution 3:[3]

Here's how to programmatically get a proper rewritten product link that includes rewritten category and product EAN code in the URL.

Of course you'll need to have $id_product and $id_lang variables properly set :

$link = new Link();
$prod = new Product($id_product);
$catRewrite = Category::getLinkRewrite((int)$prod->id_category_default, $id_lang);
$url = $link->getProductLink((int)$prod->id, $prod->link_rewrite[$id_lang], $catRewrite, $prod->ean13);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Diekmann
Solution 2 Jatniel
Solution 3 user3256843