Magento – Magento 2 get Product Url in Foreach

magento2.2.2product-urlsurl

In Magento 2, I trying to get the Product URL using this code $_product->getProductUrl (). But it is having only the first product's url to all the products. How to fix it.

Used the Following Code:

$_collection = $this->objectManager->get ( '\Magento\Catalog\Model\Product' )->getCollection ();
 $_collection = $collection->getData();
 foreach ( $_collection as $_product ) {
 $_product = $this->objectManager->get ( 'Magento\Catalog\Model\Product' )->load ( $_product['entity_id'] );

      echo $product_url = $_product->getProductUrl ();
}

Best Answer

Use this code :

=> Using object manager :

$product = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
    foreach($product as $_product){ 
       echo $_product->getProductUrl();
    }

=> Using Factory Method :

protected $_productcollectionFactory;

    public function __construct(
        ..............
        Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productcollectionFactory,
        ..............
    ) {
        parent::__construct($context);
        ..............
        $this->_productcollectionFactory = $productcollectionFactory;
        ..............

    }

    public function execute()
    {
        $product_url = [];
        $proColl = $this->_productcollectionFactory->getCollection();
        foreach($proColl as $_product){ 
           $product_url[] = $_product->getProductUrl();
        }
        print_r($product_url);
    }

=> Get url by product Id :

public function __construct(
   \Magento\Catalog\Model\ProductRepository $productRepository,
) {
  $this->_productRepository = $productRepository;
}

Then you load the product based on the product id:

public function getProductUrl($productId){
  $product = $this->_productRepository->getById($productId);
  return $product->getUrlModel()->getUrl($product);
}

Note : Don't use object manager directly

Related Topic