How To Get CMS Block Data By Identifier In Magento 2

How To Get CMS Block Data By Identifier In Magento 2

The post shows how to get CMS block data by identifier in Magento 2.

The simple method is to call the BlockRepositoryInterface interface to get the CMS static block collection by an identifier in Magento 2.

Magento\Cms\Api\BlockRepositoryInterface used to get CMS Static Blocks in Magento 2. If you want to fetch a collection of CMS static blocks or get a specific CMS static block data, use BlockRepositoryInterface.

Instantiate BlockRepositoryInterface in __construct() method of Class.

For example,

Get CMS Static Block by identifier, You need to pass identifier in searchCriteriaBuilder addFilter() method,
Let’s assume CMS Static Block identifier is contact-us-info,

$searchCriteria = $this->searchCriteriaBuilder->addFilter(‘identifier’, ‘contact-us-info’,’eq’)->create();

I have used equal conditions. However, you can set any conditions as for the third parameter in the above function as per your requirements. Refer to the list below for the same.

List of addAttributeToFilter Conditionals In Magento 2:


Method to Get CMS Block Data By Identifier in Magento 2:

Create GetCmsBlock class in Namespace\Module\Block

Now you can use the above Block class method in .phtml like

The above code gives all the CMS static block from the Magento 2 store.

Based on the above Code snippet you get all the Cms Static Blocks from the store.

That’s it.

Any doubts about the topic? Feel free to post them in the Comments section below. I’d be happy to help.

Please share the solution with fellow Magento developers via social media.

Thank you.

(based on 14 Reviews)

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. Owing to his contributions in Magento Forums and posting solutions, he is among the top 50 contributors of the Magento community in 2019. When he is not engrossed with anything related to Magento, he loves to play cricket.

Leave a Reply

(based on 5 Reviews)