0

Is there any way to select random product ID from product collection object in magento 2.3

$_productCollection = $this->getProductList($catid); How can I select random product id from this object

0

Please try with below code :

$_productCollection = $this
        ->getCategory($catid)
        ->getProductCollection()
        ->addAttributeToSelect('*')
        ->setPageSize(5);

$_productCollection->getSelect()->orderRand();

$products = $_productCollection->getItems();

hope its work for you.

  • I tried this. And my question is different. After running code given my you if i want random product id how can we do that – Nafisa Aug 22 at 7:14
0

You can use below code to get random product id from a category.

$productIds = array_column($_productCollection->getData(), 'entity_id');
$randomProductId = $productIds[array_rand($productIds)];
echo $randomProductId;

Example code in a block file:

<?php
namespace Amit\Test\Block;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\Category;

class RandomProductId extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        Category $category,
        Template\Context $context, 
        array $data = array())
    {
        $this->category = $category;
        parent::__construct($context, $data);
    }

    public function getRandomProductId($categoryId)
    {
        $productCollection = $this->category->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
        $productIds = array_column($productCollection->getData(), 'entity_id');
        $randomProductId = $productIds[array_rand($productIds)];
        return $randomProductId;
    }
}
  • thanx i am getting random product id. but on page refresh i am agian getting the same id. why so? i want the random id should be changed on every page refresh. Any idea about this? – Nafisa Aug 22 at 8:31
  • any idea about the Ajax post call? – Nafisa Aug 22 at 9:20
  • Maybe the page is cached. You can use the same code in a controller file and call using ajax as mentioned here stackoverflow.com/questions/38220376/… – amitshree Aug 22 at 9:40
  • any example in AJAX for displaying products? – Nafisa Aug 22 at 10:34
  • I believe it should be a new question. – amitshree Aug 22 at 12:02

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.