I would like to know if i can make 7-14 blocks be random throughout my sidebars?
Hi,
You could create a custom widget that will output a randomly selected block using code like this:
<?php
namespace Vendor\MyWidget\Block;
use Magento\Cms\Model\Block;
use Magento\Cms\Model\ResourceModel\Block\Collection;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
class RandomBlock extends Template
{
//An array of the ID's of the blocks you want to randomly select from.
protected $_blockIDs = [8,3];
/** @var array $_blockArray */
protected $_blockArray;
/**
* RandomBlock constructor.
* @param Context $context
* @param Collection $blockCollection
* @param array $data
*/
public function __construct(Context $context, Collection $blockCollection, array $data)
{
parent::__construct($context, $data);
$blockArray = [];
$allBlocks = $blockCollection->getItems();
for ($i=0; $i<count($this->_blockIDs); $i++) {
$blockArray[] = $allBlocks[$this->_blockIDs[$i]];
}
shuffle($blockArray);
$this->_blockArray = $blockArray;
}
/**
* Get a random block.
*
* @return Block
*/
public function getRandomBlock()
{
return array_pop($this->_blockArray);
}
}
You can then echo $block->getRandomBlock()->getContent() from within the widget's template file to output a block randomly selected from the pool of IDs defined in $_blockIDs.
If this is all gibberish to you, lemme know and I could package it up as a module.
i am in extreme learning mode on this topic, so if you truly don't mind, the more explanation i can get the better. Thank you
I'm also learning and am happy to help.
You can download the module from here: https://github.com/aaronallen8455/RandomBlock
You'll then need to do the following to get it working:
1. Place the module directory 'RandomBlock' in this location: app/code/AAllen/
Create the directories that don't exist.
2. You then need to run these shell commands from the Magento root directory to install the module:
php bin/magento setup:upgrade
php bin/magento cache:flush
3. In the Magento backend, go to Content:Widgets and add a new widget of type 'Random Block'.
4. Configure the widget with a list of the IDs of the blocks you want it to pick from and the number of blocks you want it to display.
5. Place the widget in the location you want in the layout updates and click Save.
6. Flush the cache.