0

I want to display random products on my homepage. I have been using this $collection->clear()->getSelect()->order('rand()');. My aim is the products should be displayed randomly on every page refresh. But here, this happens only after i clear cache and then refresh my page. Without cache flush, it displays same products

0

Add this line in your collection

$collection->getSelect()->orderRand();

If you are facing the cache issue, you can use in your layout file

cacheable="false";

Blocks can be set as non-cacheable by setting the cacheable attribute false in layout XML files. For example

<block class="Block\Class" name="blockname" cacheable="false" />
  • Still same issue exist. When i manually run cache clean command then only it works. Else no – Nafisa Aug 20 at 13:30
  • cacheable="false"` for home page is bad idea. If any block of a page is cacheable false then this page become Fully Non-cacheable – Amit Bera Aug 20 at 14:37
0
$productsCol = $this
        ->getCategory($id)
        ->getProductCollection()
        ->addAttributeToSelect('*')
        ->setPageSize(3);

$productsCol->getSelect()->orderRand();

$products = $productsCol->getItems();

Please check with this whole code.

I hope it will help you.

  • this does not work, as i am having cache issue. – Nafisa Aug 20 at 13:45
  • you can add cacheable="false" in your layout file. – Monark Bhawani Aug 20 at 13:47
  • Added this too, still did not work – Nafisa Aug 20 at 13:49
  • Then it's not cache issue. – Monark Bhawani Aug 20 at 13:50
  • Then what? if i manually run cache command, new products displayed on my homepage. but when i only refresh the page, same products displayed – Nafisa Aug 20 at 13:51
0

Add This Block In Home Page And Check :-

{{block class="Magento\Catalog\Block\Product\ProductList\Random" template="product/list.phtml" num_products="12"}}
  • Tried this also, still the same issue – Nafisa Aug 20 at 11:54
  • create any layout block for display random product ?? – Rk Rathod Aug 20 at 11:56
  • $category = $this->categoryFactory->create()->load($categoryId); $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->addCategoryFilter($category); $collection->getSelect()->orderRand(); – Nafisa Aug 20 at 12:01
  • how to display random product in homepage ?? – Rk Rathod Aug 20 at 12:01
  • that another template. basically $collection->getSelect()->orderRand(); i am using to select ramdom products – Nafisa Aug 20 at 12:13
0

The best idea to Ajax, On the load of this page, call a page with a POST request and return Magento\Catalog\Block\Product\ProductList\Random block content.

As Magento does calculate post request as cacheable request, So don't get any issue with the cache.

Controller Class RandomList.php

<?php

namespace StackExchange\Magento\Controller\Example;

use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\Layout;
use Magento\Framework\Controller\ResultFactory;

class RandomList  extends \Magento\Framework\App\Action\Action
{

    public function execute() 
    {
        $this->resultFactory->create(ResultFactory::TYPE_LAYOUT);
    }

}

layout files {routeID}_example_randomList.xml and code is

And code:

<?xml version="1.0"?>

<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <container name="root">
        <block class="MStackExchange\Magento\Block\Product\ProductList\Random" name="product.info.random.prp" as="products_random" template="Magento_Catalog::product/list/items.phtml" />
          <arguments>
                    <argument name="type" xsi:type="string">new</argument>
                </arguments>
    </container>
</layout>

Block Class

<?php
namespace StackExchange\Magento\Block\Product\ProductList;

use Magento\Catalog\Api\CategoryRepositoryInterface;

/**
 * Catalog product random items block
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Random extends \Magento\Catalog\Block\Product\AbstractProduct implements
    \Magento\Framework\DataObject\IdentityInterface
{

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    private $catalogProductVisibility;

    /**
     * Product collection factory
     *
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productCollectionFactory;

    /**
     * @var CategoryRepositoryInterface
     */
    protected $categoryRepository;



    /**
     * @param \Magento\Catalog\Block\Product\Context $context
     * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper
     * @param CategoryRepositoryInterface $categoryRepository
     * @param \Magento\Framework\Url\Helper\Data $urlHelper
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
     * @param array $data
     */
    public function __hconstruct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
        CategoryRepositoryInterface $categoryRepository,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,    
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
        $this->catalogProductVisibility = $catalogProductVisibility;
    }

    /**
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    protected function _getProductCollection()
    {
        if ($this->_productCollection === null) {
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
            $collection = $this->_productCollectionFactory->create();
            $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
             $collection = $this->_addProductAttributesAndPrices(
            $collection
             );
            $collection->getSelect()->order('rand()');
            $collection->addStoreFilter();

            $collection->setPage(1, 10);

            $this->_productCollection = $collection;
        }
        return $this->_productCollection;
    }

    /**
     * Return identifiers for produced content
     *
     * @return array
     */
    public function getIdentities()
    {
        return ['ran_products'];
    }
    /**
     * Prepare collection with new products
     *
     * @return \Magento\Framework\View\Element\AbstractBlock
     */
    protected function _beforeToHtml()
    {
        $this->setProductCollection($this->_getProductCollection());
        return parent::_beforeToHtml();
    }    
}
  • My code is ready. Can u just tell me what i need to add in my code for random products would be great – Nafisa Aug 21 at 5:19
  • Can u help please? – Nafisa Aug 21 at 9:07
  • Can you please tell me what changes you have done/what files you have write? – Amit Bera Aug 21 at 9:27
  • HAve created a block and called template inside that. $_productCollection = $this->getProductList($category['entity_id']) is called to get product collection. $collection->clear()->getSelect()->order('RAND()'); i am usign for random product. my issue is if i clear cache then only products get changed and not on page refresh. what can be the issue. – Nafisa Aug 21 at 9:35
  • Did u understand ? – Nafisa Aug 21 at 9:59

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.