You can get specific CMS page collection in Magento 2 by calling interface, Magento\Cms\Api\PageRepositoryInterface.
PageRepositoryInterface is used when you need to fetch a collection of CMS page 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, 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 above query, identifier used as page url key.
We have used equal conditions, You can set any conditions as the third parameter in the above conditions.
List of Conditions are,
‘eq’, ‘neq’, ‘like’, ‘nlike’, ‘in’, ‘nin’, ‘notnull’, ‘null’, ‘gt’,’lt’, ‘gteq’, ‘lteq’, ‘finset’
Example for like condition, addFilter(‘identifier’,’%test%’,’like’)
I will give you demo using creating Block Class,
<?php namespace Rbj\Pages\Block; class Pages extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Cms\Api\PageRepositoryInterface $pageRepositoryInterface, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, array $data = [] ) { $this->pageRepositoryInterface = $pageRepositoryInterface; $this->searchCriteriaBuilder = $searchCriteriaBuilder; parent::__construct($context, $data); } /** * string $urlKey * Get CMS Page Data from Page url key. **/ public function getPageData($urlKey) { if(!empty($urlKey)) $searchCriteria = $this->searchCriteriaBuilder->addFilter('identifier', $urlKey,'eq')->create(); $pages = $this->pageRepositoryInterface->getList($searchCriteria)->getItems(); return $pages; } else { return 'Page id invalid'; } }
From Template file, you need to pass Page id and based on Page id you can get Page Collection.
<?php $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.