1

I want to get 6 random product from same category on product page in magento 2

2

You can use the method orderRand() which can be applied to the select of a collection for getting random sorting.

For example in product page context you can create a block like the following, add it to your layout where you need it, and get the collection of the 6 random products calling the method getRandomItems() from your template. Please note: The approach works if the current_category is set. That's the case if your product page is called with category path. If you don't have the current_category in your context, please load the category you need. Anyway if no category is given the method returns 6 products randomly from the whole assortment.

namespace Vendor\Module\Block;

class Randomproducts extends \Magento\Catalog\Block\Product\AbstractProduct
{
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct(
            $context,
            $data
        );
    }

    public function getRandomItems()
    {
        $category = $this->_coreRegistry->registry('current_category');
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(6);
        if ($category){
            $collection->addCategoryFilter($category);
        }
        $collection->getSelect()->orderRand();

        return $collection->getItems();
    }
}

I hope that helps. Feedback would be nice :-)

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.