0

Magento2 How can I add breadcrumb dynamically on custom pages?

Home > FAQ > Carpet FAQ
Home > FAQ > Shutters FAQ

Where Carpet & Shutters are dynamic

2 Answers 2

2

You can achieve by using the below code in the block file.

  public function _prepareLayout()
        {
            $breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs');
            $baseUrl = $this->_storeManager->getStore()->getBaseUrl();
    
            if ($breadcrumbsBlock) {
    
                $breadcrumbsBlock->addCrumb(
                    'home',
                    [
                    'label' => __('FAQ'), //lable on breadCrumbes
                    'title' => __('Carpet FAQ'),
                    'link' => $baseUrl
                    ]
                );
                $breadcrumbsBlock->addCrumb(
                    'coderkube',
                    [
                    'label' => __('Carpet FAQ'),
                    'title' => __('Carpet FAQ'),
                    'link' => '' //set link path
                    ]
                );
            }
            $this->pageConfig->getTitle()->set(__('FAQ')); // set page name
            return parent::_prepareLayout();
        }
0

In your custom controller you can add breadcrumbs using below code.

resultPageFactory is Magento\Framework\View\Result\PageFactory

public function execute(){  
    $resultPage = $this->resultPageFactory->create();
    $breadcrumbsBlock = $resultPage->getLayout()->getBlock('breadcrumbs');
    if ($breadcrumbsBlock) {
        $breadcrumbsBlock->addCrumb(
            'home',
            [
                'label'    => __('Home'),
                'link'     => $this->_url->getUrl('')
            ]
        );
        $breadcrumbsBlock->addCrumb(
            'faq',
            [
                'label'    => __('Faq'),
                'link'     => $this->_url->getUrl('faq')
            ]
        );
        /* you can add here your confition for dynamic element*/
        $breadcrumbsBlock->addCrumb(
            'carpet_faq',
            [
                'label'    => __('Carpet FAQ'),
                'link'     => $this->_url->getUrl('carpetfaq')
            ]
        );
    }
    return $resultPage;
}
1
  • 1
    I tried to add via controller but not working
    – Arjun
    Sep 30, 2020 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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