0

How to get a each product id in category page? I need to get the product id in custom module template file.

enter image description here

  • i need a all product id separately – divya sekar Apr 23 at 13:11
1

Try this,

Add the below code to your block

<?php
namespace Vendor\ModuleName\Block;
class ProductCollection extends \Magento\Framework\View\Element\Template
{    
  protected $_productCollectionFactory;   
  public function __construct(
     \Magento\Backend\Block\Template\Context $context,        
     \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory 
      $productCollectionFactory,        
      array $data = []
 )
  {    
      $this->_productCollectionFactory = $productCollectionFactory;    
      parent::__construct($context, $data);
  } 
  public function getProductCollection()
  {
      $collection = $this->_productCollectionFactory->create();
      $collection->addAttributeToSelect('*');
      return $collection;
  }
}

on your template file add the below code to get all the product ids

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
  echo $product->getId();     
  echo "<br>";
}

Hope this helps.

  • Using a above code i get a product id like this prnt.sc/ng2pb3 – divya sekar Apr 24 at 5:14
  • You want to show it with the product in the sense you gotta edit list page phtml and get the id like $_product->getId(); from the there – Prathap Gunasekaran Apr 24 at 5:23
  • I tried that way but I cannot pass a product id from theme to my custom module @Prathap – divya sekar Apr 24 at 5:25
  • As of my understanding you can extend the phtml to your theme then you do like this and am not clear what do you mean custom module in order to achieve this. Please update us the complete requirement. – Prathap Gunasekaran Apr 24 at 5:27
0

If you want to have the product id in the product listing template file, then you can try following code

$_product->getId()
  • i need product id in custom module template file not in theme – divya sekar Apr 23 at 12:28
  • @divyasekar How are you showing/fetching the products? Share that code. – Anshu Mishra Apr 24 at 4:57
  • Anush I m asking about that only how to fetch each product id – divya sekar Apr 24 at 5:08
  • Using @prathap answer i get a product id like this prnt.sc/ng2pb3 – divya sekar Apr 24 at 5:13
  • @divyasekar Kindly share your code. – Anshu Mishra Apr 24 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.