0

I want to get random product from category id which is working find but i want to exclude a particluar product id from out and show output in random order

Below is my code , please help me with way i can get random order and exclude product id

$cateinstance = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
$cateid = $allcatsmain;
$allcategoryproduct = $cateinstance->create()->load($cateid)->getProductCollection()->setPageSize(4)->addAttributeToSelect('*');
3

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!

  • Did you tried this then ? – Kishan Savaliya Oct 20 at 10:52
  • 2
    This answers question perfectly. Although would be good to see solution that doesn't use object manager or better yet searching with repositories – Dominic Xigen Oct 20 at 18:56
  • Is above solution helpful to you ? If YES then please approve my answer. Thanks :) – Kishan Savaliya Oct 22 at 14:21

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.