You can use this script to get category product collection randomly and you can exclude items which is not require..
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryInstance = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
$categoryId = 4;
$excludeProductIds = array(2,3,4,5,6);
$filteredProductCollection = $categoryInstance->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*')->setPageSize(15)->addFieldToFilter('entity_id', array('nin' => $excludeProductIds));
$filteredProductCollection->getSelect()->orderRand();
$filteredProductCollection->getItems();
foreach ($filteredProductCollection as $product) {
echo $product->getId()." => ".$product->getName();
echo "<br/>";
}
?>
You can use below code instead of using $objectManager
directly..
<?php
protected $_categoryFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
$this->_categoryFactory = $categoryFactory;
}
public function execute()
{
$categoryId = 4;
$excludeProductIds = array(2,3,4,5,6);
$filteredProductCollection = $this->_categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*')->setPageSize(15)->addFieldToFilter('entity_id', array('nin' => $excludeProductIds));
$filteredProductCollection->getSelect()->orderRand();
$filteredProductCollection->getItems();
foreach ($filteredProductCollection as $product) {
echo $product->getId()." => ".$product->getName();
echo "<br/>";
}
}
?>
Hope this will help you!