You can get CMS Static Blocks collection by an identifier in Magento 2 by calling BlockRepositoryInterface interface.
Magento\Cms\Api\BlockRepositoryInterface used for getting CMS Static Blocks in Magento 2.
BlockRepositoryInterface is used when you need to fetch a collection of CMS Static blocks or get specific CMS static block data.
You need to instantiate BlockRepositoryInterface in __construct() method of Class.
I wil give you demo using Block Class,
Get CMS Static Block by identifier, You need to pass identifier in searchCriteriaBuilder addFilter() method,
Let’s assume CMS Static Block identifier is footer_links_block,
$searchCriteria = $this->searchCriteriaBuilder->addFilter(‘identifier’, ‘footer_links_block’,’eq’)->create();
We have used equal conditions, You can set any conditions as third parameter in above function as per your needs.
List of Conditions are, ‘eq’,’neq’,’like’,’nlike’,’in’,’nin’,’notnull’,’null’,’gt’,’lt’,’gteq’,’lteq’,’finset’
<?php namespace Rbj\CmsBlock\Block; class CmsBlock extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Cms\Api\BlockRepositoryInterface $blockRepository, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, array $data = [] ) { $this->blockRepository = $blockRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; parent::__construct($context, $data); } /* Get Cms Blocks Collection from store. */ public function getCmsBlock() { $searchCriteria = $this->searchCriteriaBuilder->addFilter('identifier', 'footer_links_block','eq')->create(); $cmsBlock = $this->blockRepository->getList($searchCriteria)->getItems(); return $cmsBlock; }
From Template file, You can access all the Static Block by an iterating loa op over a collection.
<?php $cmsBlocks = $block->getCmsBlock(); foreach($cmsBlocks as $cmsBlock) { echo $cmsBlock->getId(); // get Id echo $cmsBlock->getTitle(); // get Title/name of CMS Static Block //echo "<pre>";print_r($cmsBlock->getData()); } ?>
Based on above Code snippet you get all the Cms Static Blocks from store. You can also get specific Static Blocks based on your custom condition by refer link.