0

i want to random 5 category but not luck for me

i have use below code

$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()->addAttributeToSelect('*')->setPageSize(5)->getSelect()->orderRand();

Note: order random not working for me

  • Your requirement is something like every page refresh 5 category random display? – Rohan Hapani Jul 5 at 11:35
  • no i want to get custom page in random 5 category get – Rakesh Donga Jul 5 at 11:53
  • Sorry. But, your question and last comment don't match. Can you please elaborate more in question? – Rohan Hapani Jul 5 at 11:59
  • @RohanHapani i want to get random 5 category in homepage you got it ? – Rakesh Donga Jul 5 at 12:00
  • @RakeshDonda please check my updated answer. – Rohan Hapani Jul 8 at 5:25
0

I know it's not proper solution. But, It maybe helpful for you. Try to use this below code :

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
    $categories = $categoryFactory->create()->addAttributeToSelect('*');
    $cat_arr = $categories->getData();
    $random_keys = array_rand($cat_arr, 5);
    $cat_ids = [];
    foreach ($random_keys as $key => $value) {
        $cat_ids[] = $cat_arr[$value]['entity_id'];
    }
    $cat_rand_obj = $categoryFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', ['in' => $cat_ids]);
    echo "<pre>";
    print_r($cat_rand_obj->getData());

Note: Avoid to use object manager. Use Factory Method structure.

  • not working for me – Rakesh Donga Jul 5 at 12:13
  • Is it working for you? – Rohan Hapani Jul 8 at 7:27
  • Okay. If it's working then, please mark as accept and upvote. So, It will helpful for others. – Rohan Hapani Jul 8 at 10:13

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.