1

Is there any workaround to show the fullpath with category and subcategories in the breadcrumb on the product detail page?

It now only shows: Home > Product "myproduct"

3 Answers 3

4

Module Method Working For me in Magento 2.1 / 2.2 /2.3 :: Show Fullpath in BreadCrumb On Product Detail Page(Home > Category1 > Category2 > MyProduct).Also Works on MegaMenu

  1. app/code/[VendorName]/[ModuleName]/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[VendorName_ModuleName]',
    __DIR__
);
  1. app/code/[VendorName]/[ModuleName]/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[VendorName_ModuleName]" setup_version="0.1.1">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Magento_Theme"/>
        </sequence>
    </module>
</config>
  1. app/code/[VendorName]/[ModuleName]/etc/frontend/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Controller\Product\View">
        <plugin name="[VendorName_ModuleName]_product_breadcrumbs" type="[VendorName]\[ModuleName]\Plugin\Product\View" sortOrder="1"/>
    </type>
</config>
  1. app/code/[VendorName]/[ModuleName]/Plugin/Product/View.php
<?php

namespace [VendorName]\[ModuleName]\Plugin\Product;

use Magento\Catalog\Controller\Product\View as MagentoView;
use Magento\Catalog\Model\Product;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManager;
use Magento\Framework\Registry;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Model\ResourceModel\Category\Collection;
use Magento\Framework\View\Result\Page;

class View
{

    /**
     * @var Product
     */
    protected $product;
    /**
     * @var StoreManager
     */
    protected $storeManager;
    /**
     * @var Registry
     */
    protected $registry;
    /**
     * @var Collection
     */
    protected $collection;
    /**
     * @var PageFactory
     */
    private $resultPage;


    /**
     * View constructor.
     * @param StoreManager $storeManager
     * @param Registry $registry
     * @param Collection $collection
     * @param PageFactory $resultPage
     */
    public function __construct(
        StoreManager $storeManager,
        Registry $registry,
        Collection $collection,
        PageFactory $resultPage)
    {
        $this->storeManager = $storeManager;
        $this->registry = $registry;
        $this->collection = $collection;
        $this->resultPage = $resultPage;
    }

    public function afterExecute(MagentoView $subject, $result)
    {
        if(!$result instanceof Page){
            return $result;
        }

        $resultPage = $this->resultPage->create();
        $breadcrumbsBlock = $resultPage->getLayout()->getBlock('breadcrumbs');
        if(!$breadcrumbsBlock || !isset($breadcrumbsBlock)){
            return $result;

        }
        $breadcrumbsBlock->addCrumb(
            'home',
            [
                'label' => __('Home'),
                'title' => __('Go to Home Page'),
                'link' => $this->storeManager->getStore()->getBaseUrl()
            ]
        );

        try {
            $product = $this->getProduct();
        } catch (LocalizedException $e) {
            return $result;
        }
        
        $pageMainTitle = $resultPage->getLayout()->getBlock('page.main.title');
        if ($pageMainTitle) {
            $pageMainTitle->setPageTitle($product->getName());
        }

        if(null == $product->getCategory() || null == $product->getCategory()->getPath()){
            $breadcrumbsBlock->addCrumb(
                'cms_page',
                [
                    'label' => $product->getName(),
                    'title' => $product->getName(),
                ]
            );
            return $result;
        }

        $categories = $product->getCategory()->getPath();
        $categoriesids = explode('/', $categories);

        $categoriesCollection = null;
        try {
            $categoriesCollection = $this->collection
                ->addFieldToFilter('entity_id', array('in' => $categoriesids))
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('url_key')
                ->addAttributeToSelect('include_in_menu')
                ->addAttributeToSelect('is_active')
                ->addAttributeToSelect('is_anchor');
        } catch (LocalizedException $e) {
            return $result;
        }

        foreach ($categoriesCollection->getItems() as $category) {
            if ($category->getIsActive() && $category->isInRootCategoryList()) {
                $categoryId = $category->getId();
                $path = [
                    'label' => $category->getName(),
                    'link' => $category->getUrl() ? $category->getUrl() : ''
                ];
                $breadcrumbsBlock->addCrumb('category' . $categoryId, $path);
            }
        }

        $breadcrumbsBlock->addCrumb(
            'cms_page',
            [
                'label' => $product->getName(),
                'title' => $product->getName(),
            ]
        );

        return $result;
    }

    /**
     * @return Product
     * @throws LocalizedException
     */
    private function getProduct()
    {
        if (is_null($this->product)) {
            $this->product = $this->registry->registry('product');

            if (!$this->product->getId()) {
                throw new LocalizedException(__('Failed to initialize product'));
            }
        }

        return $this->product;
    }
}

5.app/code/[VendorName]/[ModuleName]/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="breadcrumbs" template="Magento_Theme::html/breadcrumbs.phtml"/>
    </body>
</page>
3
  • it worked for me when adding the di.xml in the /etc/frontend/ directory. Aug 10, 2020 at 13:14
  • 1
    Hey, thanks for the update, It was a typing mistake. I updated my answer now. Aug 12, 2020 at 12:34
  • Thank you. It worked version 2.3.4.
    – River
    Aug 20, 2020 at 4:35
0

By default, Magento shows the breadcrumbs on the basis of the path from where the user arrives at the product/category page.

Suppose, a product X has been assigned to:

  • Category A
  • Category A >> Subcategory B

If the user reaches at the product by navigating through Category A only, then the breadcrumbs will show like:

  • Home >> Category A >> product X

If the user reaches at the product by navigating through Category A, then Subcategory B, then the breadcrumbs will show like:

  • Home >> Category A >> Subcategory B >> product X

and if the user reaches at the product by searching, the breadcrumbs will look like:

  • Home >> product X

I hope it is clear now.

1
  • 1
    I know it. I am using a 3rd party extension (megamenu). I think, there are not using the default navigation, therefore Magento2 doesnt display the categories.
    – Marcel
    Jan 12, 2019 at 10:19
0

-If you are using some extra module like megamenu. In this case just replace your block with this.

<?php

namespace VenorName\ModuleName\Block;

use Magento\Catalog\Helper\Data;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\Store;
use Magento\Framework\Registry;
use Magento\Framework\App\Config\ScopeConfigInterface;
class Crumbs extends \Magento\Framework\View\Element\Template
{
    private $catalogData = null;

    private $scopeConfig;

    public function __construct(
        Context $context,
        Data $catalogData,
        Registry $registry,
        ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\Request\Http $request,
        array $data = []
    ) {
        $this->catalogData = $catalogData;
        $this->registry = $registry;
        $this->request = $request;
        $this->scopeConfig = $scopeConfig;
        parent::__construct($context, $data);
    }

    public function getCrumbs()
    {
        $evercrumbs = array();

        $evercrumbs[] = array(
            'label' => 'Home',
            'title' => 'Go to Home Page',
            'link' => $this->_storeManager->getStore()->getBaseUrl()
        );
    
        $product = $this->registry->registry('current_product');
    
        $categoryCollection = clone $product->getCategoryCollection();
        $categoryCollection->clear();
        $categoryCollection->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)->addAttributeToFilter('path', array('like' => "1/" . $this->_storeManager->getStore()->getRootCategoryId() . "/%"));
        $categoryCollection->setPageSize(1);
        $breadcrumbCategories = $categoryCollection->getFirstItem()->getParentCategories();
        foreach ($breadcrumbCategories as $category) {
            $evercrumbs[] = array(
                'label' => $category->getName(),
                'title' => $category->getName(),
                'link' => $category->getUrl()
            );
        }
    
        $evercrumbs[] = array(
                'label' => $product->getName(),
                'title' => $product->getName(),
                'link' => ''
            );
    
        return $evercrumbs;
}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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