How to show breadcrumbs on product pages even if opened directly via search

In this post, we will learn how to show breadcrumbs on all product pages even if opened directly via search.

Also, breadcrumbs are always present rather than normally where they can get cached without a trail in Magento 2.

Let’s start step by step to show Breadcrumbs on the product page.

Step 1: To create a custom module with required files. Mageclues_Breadrcumbs

Step 2: create block class file Breadcrumbs.php at app/code/Mageclues/Breadcrumbs/Block/Breadcrumbs.php

<?php

namespace Mageclues\Breadcrumbs\Block;

use Magento\Catalog\Helper\Data;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class Breadcrumbs extends Template
{
    protected ?Data $catalogData = null;
    private Registry $registry;

    public function __construct(
        Context $context,
        Data $catalogData,
        Registry $registry,
        array $data = []
    ) {
        $this->catalogData = $catalogData;
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    private function getRootCategoryId(): int
    {
        return (int) $this->_storeManager->getStore()->getRootCategoryId();
    }

    public function getBreadcrumbs(): array
    {
        $breadcrumbs = [];
        $breadcrumbs[] = [
            'label' => __('Home'),
            'title' => __('Go to Home Page'),
            'link' => $this->_storeManager->getStore()->getBaseUrl()
        ];

        $product = $this->registry->registry('current_product');
        $categoryCollection = clone $product->getCategoryCollection();
        $categoryCollection->clear()
            ->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)
            ->addAttributeToFilter('path', ['like' => "1/" . $this->getRootCategoryId() . "/%"])
            ->setPageSize(1);

        $breadcrumbCategories = $categoryCollection->getFirstItem()->getParentCategories();
        usort($breadcrumbCategories, function ($a, $b) {
            return strcmp($a->getLevel(), $b->getLevel());
        });
        foreach ($breadcrumbCategories as $category) {
            $breadcrumbs[] = [
                'label' => $category->getName(),
                'title' => $category->getName(),
                'link'  => $category->getUrl()
            ];
        }

        $breadcrumbs[] = [
            'label' => $product->getName(),
            'title' => $product->getName(),
            'link' => ''
        ];

        return $breadcrumbs;
    }
}

Step 3: create template file breadcrumbs.phtml at app/code/Mageclues/Breadcrumbs/view/frontend/templates/breadcrumbs.phtml

<?php
/** @var \Mageclues\Breadcrumbs\Block\Breadcrumbs $block */
$Breadcrumbs = $block->getBreadcrumbs(); ?>

<?php if ($Breadcrumbs && is_array($Breadcrumbs)): ?>
<?php $i = 0; ?>
<div class="breadcrumbs">
    <ul class="items" itemscope itemtype="http://schema.org/BreadcrumbList">
        <?php foreach ($Breadcrumbs as $breadcrumbsName => $breadcrumbsInfo) : ?>
            <?php $i++; ?>
            <li class="item <?= /* @escapeNotVerified */ $breadcrumbsName ?>" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
            <?php if ($breadcrumbsInfo['link']) : ?>
                <a itemprop="item" href="<?= /* @escapeNotVerified */ $breadcrumbsInfo['link'] ?>" title="<?= $block->escapeHtml($breadcrumbsInfo['title']) ?>">
                  <span itemprop="name"><?= $block->escapeHtml($breadcrumbsInfo['label']) ?></span>
                </a>
            <?php else: ?>
				<span itemprop="name"><?= $block->escapeHtml($breadcrumbsInfo['label']) ?></span>
                <meta itemprop="item" content="<?= /* @escapeNotVerified */ $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]) ?>" />
            <?php endif; ?>
                <meta itemprop="position" content="<?= $i ?>" />
            </li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

Step 4: We need to set the template  in block by product page layout.
app/code/Mageclues/Breadcrumbs/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
		<referenceBlock class="Mageclues\Breadcrumbs\Block\Breadcrumbs" name="Breadcrumbs"  template="Mageclues_Breadcrumbs::Breadcrumbs.phtml" />
    </body>
</page>

That’s it.

I hope this blog is useful for you. Please leave a comment for the query and review.

Thank you!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *