Site icon MageComp Blog

How to Get CMS Block Collection in Magento 2?

How to Get CMS Block Collection in Magento 2

Hello Magento Friends,

In today’s blog, we will learn How to Get CMS Block Collection in Magento 2.

One of the key features of Magento 2 is the Content Management System (CMS), which enables you to create and manage static content such as pages and blocks. In this blog post, we will focus on how to retrieve a collection of CMS blocks in Magento 2 programmatically.

Before starting with obtaining CMS blocks collection, check out the below links

Let’s jump into the steps to get CMS block collection in Magento 2.

Steps to Get CMS Block Collection in Magento 2:

Step 1: Create a CmsBlockcollection.php file inside the Block folder.

app\code\Vendor\Extension\Block

Now add the code as follows.

<?php
namespace Vendor\Extension\Block;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;

class CmsBlockcollection extends \Magento\Framework\View\Element\Template
{
   protected $blockRepository;
   protected $searchCriteriaBuilder;

   public function __construct(
         \Magento\Framework\View\Element\Template\Context $context,
         BlockRepositoryInterface $blockRepository,
         SearchCriteriaBuilder $searchCriteriaBuilder,
         array $data = []
         )
   {
       $this->blockRepository = $blockRepository;
       $this->searchCriteriaBuilder = $searchCriteriaBuilder;
       parent::__construct($context, $data);
   }
      public function getCmsBlockcollection() {
        $searchCriteria = $this->searchCriteriaBuilder->create();
        $cmsBlockscollection = $this->blockRepository->getList($searchCriteria)->getItems();
        return $cmsBlockscollection;
    }
}

Step 2: Now, get all CMS block collection in phtml file using the below code.

<?php
	$cmsBlockscollection = $block->getCmsBlockcollection();
	foreach($cmsBlockscollection as $cmsBlock) {
	    echo $cmsBlock->getTitle(); 
	    echo $cmsBlock->getId();
           print_r($cmsBlock->getData());
	}
?>

Conclusion:

This way, you can retrieve CMS block collection in Magento 2. If you have any doubt, let me know through the comment box. Share the tutorial with your friends and stay in touch with us.

Happy Coding!

Exit mobile version