1

In a page template (.phtml) file, we can generate a link to another CMS page using the following snippet:

<a href="<?php echo $this->getUrl('my_page_url_key');?>">Link to my page</a>

But is it possible to have a link generated if we know the ID of the page? Example:

<a href="<?php echo $this->getUrl(3);?>">Link to my page with ID 3</a>

This way the admin can change url key without breaking the theme links.

  • 1
    @Rakesh Not at all. I'm not asking for the current page! There is a hint in your answer, though: $page = $this->pageRepository->getById($pageId); $url = $page->getIdentifier();which I will try. – Design by Adrian Oct 26 '16 at 15:40
  • @Rakesh No, the block I'm using doesn't implement the pageReposity class. I could overload the class with my own, I suppose, but that's overkill for just one link. – Design by Adrian Oct 26 '16 at 15:46
11

By using object manager you can get CMS page url, if you have already id of cms page.

$pageId = 1;
$this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

or 

$this->_objectManager = $block->_objectManager;
$CMSPageURL = $this->_objectManager->create('Magento\Cms\Helper\Page')
->getPageUrl($pageId);

you can call object manager in your block using

protected $_objectManager;
public function __construct( 
... 
\Magento\Framework\ObjectManagerInterface $objectmanager, 
... ) { 
      ... 
      $this->_objectManager = $objectmanager; 
      ... 
}

May be it will help you, thanks.

  • This works! :) But I'm worried about using the objectManager like that, as I've read that it's discouraged? – Design by Adrian Oct 26 '16 at 15:47
  • if you have used custom block then you can call block variable of object manager, like $block->_objectManager in phtml; public function __construct(\Magento\Framework\View\Element\Template\Context $context, array $data = array()) { $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); parent::__construct($context, $data); } or public function __construct( ... \Magento\Framework\ObjectManagerInterface $objectmanager, ... ) { ... $this->_objectManager = $objectmanager; ... } – chirag Oct 27 '16 at 4:38
  • Check my updated answer. – chirag Oct 27 '16 at 12:23
  • Thank you, @chirag I'm marking your reply as the answer. I will use your suggestion as it's the best one I've seen so far, and doesn't look that offensive. I'd be happy for someone to explain when it's okay to use the object manager, and when it's not! – Design by Adrian Oct 27 '16 at 12:28
  • For everyone who thinks this is a good example - it's not. Instead of declaring object manager in the constructor - declare object that you want to call, in this case 'Magento\Cms\Helper\Page'. Moreover - do not call/declare objectmanager if you do not know how it is need to be used. – Macas Jun 25 '18 at 15:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.