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
Please try with below code :
$_productCollection = $this
->getCategory($catid)
->getProductCollection()
->addAttributeToSelect('*')
->setPageSize(5);
$_productCollection->getSelect()->orderRand();
$products = $_productCollection->getItems();
hope its work for you.
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;
}
}