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

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

1 Answer 1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.