You can get specific CMS page collections in Magento 2 by calling interface, Magento\Cms\Api\PageRepositoryInterface.
PageRepositoryInterface is used when you need to fetch a collection of CMS pages or get specific CMS page data.
You need to instantiate PageRepositoryInterface in __construct() method of Class. If you want to Get All CMS Pages Collection refer to Get All CMS Pages Collection Magento 2
To access Pages Collection by URL key, Filter page collection by identifier,
$searchCriteria = $this->searchCriteriaBuilder->addFilter(‘identifier’, ‘about-us’,’eq’)->create();
In the above query, the identifier is used as the page URL key.
We have used equal conditions, You can set any conditions as the third parameter in the above conditions. The list of Conditions you can used,
‘eq’, ‘neq’, ‘like’, ‘nlike’, ‘in’, ‘nin’, ‘notnull’, ‘null’, ‘gt’,’lt’, ‘gteq’, ‘lteq’, ‘finset’
Example for like condition, addFilter(‘identifier’,’%test%’,’like’)
Code Sample,
<?php declare(strict_types=1); namespace Rbj\Pages\Model; use Magento\Cms\Api\PageRepositoryInterface; use Magento\Framework\Api\SearchCriteriaBuilder; class Pages { public function __construct( private readonly PageRepositoryInterface $pageRepositoryInterface, private readonly SearchCriteriaBuilder $searchCriteriaBuilder ) { } /** * string $urlKey * Get CMS Page Data from Page url key. **/ public function getPageData(string $urlKey): array { $pages = []; if ($urlKey) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('identifier', $urlKey, 'eq')->create(); $pages = $this->pageRepositoryInterface->getList($searchCriteria)->getItems(); } return $pages; } }
From the Template file, you need to pass Page ID, and based on that you can get Page Collection.
$urlKey = 'about-us'; $pages = $block->getPageData($urlKey); if (count($pages)) { foreach ($pages as $page) { echo $page->getContent(); // get Content echo $page->getTitle(); // get Title/name of CMS Page } }
Based on the above Code snippet you get all the page data from page url_key.