0

I want to add a category name in bread crumb in product detail page?. Can you help me how to do that?

Here is the example I want it.

Home > Main Category Name > Sub category name > Product name

Currently, I can see like this:

Home > Product name

But, need to add a category into that.

Thanks you in advance!

2 Answers 2

0

Try this

app/design/frontend/VendorTheme/ThemeName/Magento_Catalog/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page>
<body>
    <referenceBlock name="breadcrumbs" remove="true" />
    <referenceContainer name="page.top">
        <block class="Vendor\Module\Block\Breadcrumbs" name="product.view.breadcrumbs" template="Magento_Theme::html/breadcrumbs.phtml" />       
    </referenceContainer>
</body>
</page>

app/design/frontend/VendorTheme/ThemeName/Magento_Theme/templates/html/breadcrumbs.phtml

<?php $crumbs = $block->getBreadcrumb(); ?>
<?php if ($crumbs && is_array($crumbs)) : ?>
    <div class="breadcrumbs">
        <ul class="items">
            <?php foreach ($crumbs as $crumbName => $crumbInfo) : ?>
                <li class="item <?= /* @escapeNotVerified */ $crumbName ?>">
                    <?php if ($crumbInfo['link']) : ?>
                        <a href="<?= /* @escapeNotVerified */ $crumbInfo['link'] ?>" title="<?= $block->escapeHtml($crumbInfo['title']) ?>"><?= $block->escapeHtml($crumbInfo['label']) ?></a>
                    <?php else: ?>
                        <?= $block->escapeHtml($crumbInfo['label']) ?>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

App/Code/Vendor/Module/Block/Breadcrumbs.php:

<?php

namespace Vender\Module\Block;

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

class Breadcrumbs extends \Magento\Theme\Block\Html\Breadcrumbs
{

    /**
     * Catalog data
     *
     * @var Data
     */
    protected $_catalogData = null;
    protected $path = array();

    /**
     * @param Context $context
     * @param Data $catalogData
     * @param array $data
     */
    public function __construct(Context $context, Data $catalogData, array $data = [])
    {
        $this->_catalogData = $catalogData;
        parent::__construct($context, $data);
    }

    public function getTitleSeparator($store = null)
    {
        $separator = (string) $this->_scopeConfig->getValue('catalog/seo/title_separator', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store);
        return ' ' . $separator . ' ';
    }

    public function getBreadcrumb()
    {
        $this->addCrumb(
                'home', [
            'label' => __('Home'),
            'title' => __('Go to Home Page'),
            'link' => $this->getBaseUrl()
                ]
        );
        foreach ((array) $this->path as $name => $breadcrumb) {
            $this->addCrumb($name, $breadcrumb);
        }
        return $this->getCrumbs();
    }

    protected function _prepareLayout()
    {
        $this->path = $this->_catalogData->getBreadcrumbPath();
        $title = [];
        foreach ((array) $this->path as $name => $breadcrumb) {
            $title[] = $breadcrumb['label'];
        }
        return $this->pageConfig->getTitle()->set(join($this->getTitleSeparator(), array_reverse($title)));
        //return parent::_prepareLayout();
    }

    public function getCrumbs()
    {
        return $this->_crumbs;
    }

    public function getBaseUrl()
    {
        return $this->_storeManager->getStore()->getBaseUrl();
    }

}
0

You need to create module for this. I've created, try this:-

app/code/Vendor/Module/etc/module.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0"></module>
</config>

app/code/Vendor/Module/Block/Product/FullBreadcrumbs.php

<?php
/**
 * Copyright © EAdesign by Eco Active S.R.L.,All rights reserved.
 * See LICENSE for license details.
 */
namespace Vendor\Module\Block\Product;

use Magento\Catalog\Helper\Data;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\Registry;
use Magento\Framework\Api\AttributeValue;

class FullBreadcrumbs extends \Magento\Framework\View\Element\Template
{
    /**
     * Catalog data
     *
     * @var Data
     */
    private $catalogData = null;
    private $registry;
    private $categoryCollection;
    private $categoryFactory;

    /**
     * @param Context $context
     * @param Data $catalogData
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $catalogData,
        CategoryFactory $categoryFactory,
        Registry $registry,
        CollectionFactory $categoryCollection,
        array $data = []
    ) {
        $this->catalogData = $catalogData;
        $this->categoryFactory = $categoryFactory;
        $this->registry = $registry;
        $this->categoryCollection = $categoryCollection;
        parent::__construct($context, $data);
    }

    public function getProduct()
    {
        return $this->registry->registry('current_product');
    }

    public function getCategory($categoryId)
    {
        $this->category = $this->categoryFactory->create();
        $this->category->load($categoryId);
        return $this->category;
    }

    public function getCategoryProductIds($product)
    {
        /** @var  $categoryIds  AttributeValue */
        $categoriesIds = [];
        $categoryIds = $product->getCategoryIds();
        foreach($categoryIds as $categoryId){
            $categoryData = $this->getCategory($categoryId);
            $parentCategories = $categoryData->getparent_id();
            foreach($categoryData->getParentCategories() as $parent){
                array_push($categoriesIds, $parent->getId());
            }
        }
        return $categoriesIds;
    }

    public function getFilteredCollection($categoryIds)
    {
        $collection = $this->categoryCollection->create();
        $filtered_colection = $collection
            ->addFieldToSelect('*')
            ->addFieldToFilter(
                'entity_id',
                ['in' => $categoryIds]
            )
            ->setOrder('level', 'ASC')
            ->load();
        return $filtered_colection;
    }

    public function getCategories($filtered_colection)
    {
        $categories = '';
        foreach ($filtered_colection as $categoriesData) {
            $categories .= '<li class="item category'. $categoriesData->getId() .'">';
            $categories .= '<a href="' . $categoriesData->getUrl() . '" title="'. $categoriesData->getData('name') .'">';
            $categories .= $categoriesData->getData('name') . '</a>';
            $categories .= '</li>';
        }
        return $categories;
    }

    public function getProductBreadcrumbs()
    {
        $product = $this->getProduct();
        $categoryIds = $this->getCategoryProductIds($product);

        $filtered_colection = $this->getFilteredCollection($categoryIds);

        $categories = $this->getCategories($filtered_colection);

        $home_url = '<li class="item home"><a href="' . $this->_storeManager->getStore()->getBaseUrl() . '" title="'.__("Home").'">'.__("Home").'</a></li>';
        $product_name = '<li class="item product"><strong>' . $product->getName() . '</strong></li>';
        return $home_url . $categories . $product_name;
    }
}

app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0" ?>
<!--
/**
 * Copyright © EAdesign by Eco Active S.R.L.,All rights reserved.
 * See LICENSE for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="breadcrumbs">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Vendor_Module::product/breadcrumbs.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

app/code/Vendor/Module/view/frontend/templates/product/breadcrumbs.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * @var $block Vendor\Module\Block\Product\FullBreadcrumbs
 */

// @codingStandardsIgnoreFile

?>
<?php
$blockObj= $block->getLayout()->createBlock('Vendor\Module\Block\Product\FullBreadcrumbs');
$fullbreadcrumbs = $blockObj->getProductBreadcrumbs();
?>
<div class="breadcrumbs">
    <ul class="items">
        <?= /* @escapeNotVerified */ $fullbreadcrumbs ?>
    </ul>
</div>

Thanks :)

Your Answer

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

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