1

If I open category,subcategory and vertical the breadcrumbs that are showing properly

For reference please find the attached image.

enter image description here

If I open product from home page then breadcrumbs are not showing complete path. It is showing only Home and product name

For reference please find the attached image. enter image description here

I need complete path like

Home -> Category -> Subcategory -> Vetical -> product name

How can I get this one ?

Thank you.

4
  • Did you enter the product page via search or via the product listing page/category page?
    – Klettseb
    Jan 31, 2020 at 4:51
  • via product listing page/category page Jan 31, 2020 at 4:53
  • Using any external service to serve category page ? Vanilla Magento shows the breadcrumb coming from the category page. Out of the box from whatever category a user comes the breadcrumb is shown, except if you have a custom theme which changes this.
    – Klettseb
    Jan 31, 2020 at 4:59
  • I got solution from this link magento.stackexchange.com/questions/295742/… Jan 31, 2020 at 5:42

2 Answers 2

0

You need to customize your breadcrumb, it will work even if you open product from home page

First you have to add block in your module

Path: app\code\Vendor\Module\Block\Crumbblock.php

<?php
namespace Vendor\Module\Block;

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

class Crumbblock extends \Magento\Framework\View\Element\Template
{

    /**
     * Catalog data
     *
     * @var Data
     */
    protected $_catalogData = null;

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

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

        $evercrumbs[] = array(
            'label' => 'Home',
            'title' => 'Go to Home Page',
            'link' => $this->_storeManager->getStore()->getBaseUrl()
        );

        $path = $this->_catalogData->getBreadcrumbPath();
        $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;
    }
}

After that add layout file catalog_product_view.xml in your module
Path should be: app\code\Vendor\Module\view\frontend\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\Crumbblock" name="crumbs" as="crumbs" template="Vendor_Module::crumbs.phtml" />
    </referenceContainer>
    </body>
</page>

After that Add phtml file in your module Path Should be like: app\code\Vendor\Module\view\frontend\templates\crumbs.phtml

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

I hope this will help

0

there is a few variants to get BreadCrumbs from the box in Magento

  1. If product has category path in URL
  2. Referer ( config )

Magento ver. 2.4.5

but I find diper category and get Path from there

required

  1. Plugin for Magento\Catalog\ViewModel\Product\Breadcrumbs
    
        
    

file Vendor\Module\Plugin\ViewModel\Product\Breadcrumbs


namespace Vendor\Module\Plugin\ViewModel\Product;

use Magento\Catalog\Api\ProductLinkRepositoryInterface;
use Magento\Framework\Escaper;
use Magento\Framework\Serialize\Serializer\JsonHexTag;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Session as CatalogSession;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManager;

class Breadcrumbs
{
    protected $registry;
    /**
     * @var Escaper
     */
    protected $escaper;
    /**
     * @var JsonHexTag
     */
    protected $jsonSerializer;
    /**
     * @var CatalogSession
     */
    private $catalogSession;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * Current Product
     *
     * @var ProductInterface
     */
    private $currentProduct;
    /**
     * @var StoreManager
     */
    protected $storeManager;
    /**
     * @var ProductLinkRepositoryInterface
     */
    protected $productLinkRepository;

    /**
     * @param CatalogSession $catalogSession
     * @param ProductRepositoryInterface $productRepository
     * @param Escaper $escaper
     * @param JsonHexTag $jsonSerializer
     * @param ProductLinkRepositoryInterface $productLinkRepository
     * @param StoreManager $storeManager
     */
    public function __construct(
        CatalogSession $catalogSession,
        ProductRepositoryInterface $productRepository,
        Escaper $escaper,
        JsonHexTag $jsonSerializer,
        ProductLinkRepositoryInterface $productLinkRepository,
        StoreManager $storeManager
    ) {
        $this->catalogSession = $catalogSession;
        $this->productRepository = $productRepository;
        $this->escaper = $escaper;
        $this->jsonSerializer = $jsonSerializer;
        $this->productLinkRepository = $productLinkRepository;
        $this->storeManager = $storeManager;
    }

    /**
     * @param $subject
     * @param $result
     * @return string
     * @throws NoSuchEntityException
     */
    public function afterGetJsonConfigurationHtmlEscaped($subject, $result): string
    {
        $resultData = $result;
        if($categoryUrl = $this->getCategoryUrl()) {
            $data = $this->jsonSerializer->unserialize($result);
            if (is_array($data) && key_exists('breadcrumbs',$data)) {
                $data['breadcrumbs']['alternativeReferrer'] = trim($categoryUrl);
                $resultData = $this->jsonSerializer->serialize($data);
            }
        }

        return $resultData;
    }

    /**
     * @return false
     * @throws NoSuchEntityException
     */
    public function getCategoryUrl()
    {
        $categoryUrl = false;
        if ($category = $this->getDipperCategory()) {
            $categoryUrl = $category->getUrl();
        }

        return $categoryUrl;
    }

    /**
     * @return mixed
     * @throws NoSuchEntityException
     */
    public function getDipperCategory()
    {
        $currentProduct = $this->getProduct();
        $categoryCollection = clone $currentProduct->getCategoryCollection();
        $categoryCollection->clear();
        $categoryCollection->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)
            ->addAttributeToFilter('path', array('like' => "1/" . $this->storeManager->getStore()->getRootCategoryId() . "/%"));
        $categoryCollection->setPageSize(1);
        $dipperCategory = $categoryCollection->getFirstItem();

        return $dipperCategory;
    }

    /**
     * @return ProductInterface
     * @throws NoSuchEntityException
     */
    public function getProduct(): ProductInterface
    {
        if (!isset($this->currentProduct)) {
            $productId = $this->getProductId();

            if ($productId) {
                $this->currentProduct = $this->productRepository->getById($productId);
            }
        }
        return $this->currentProduct;
    }

    /**
     * @return string
     */
    public function getProductId(): string
    {
        return $this->catalogSession->getData('last_viewed_product_id');
    }
}
  1. Need or add file to theme Or make mixin

Magento_Catalog::js/product/breadcrumbs.js

change Options section

 options: {
                categoryUrlSuffix: '',
                useCategoryPathInUrl: false,
                product: '',
                categoryItemSelector: '.category-item',
                menuContainer: '[data-action="navigation"] > ul',
                alternativeReferrer: 'alternativeReferrer'
            },

and change function

 _resolveCategoryUrl: function () {
                var categoryUrl;
                var alternativeReferrer=this.options.alternativeReferrer;

                if (this.options.useCategoryPathInUrl) {
                    // In case category path is used in product url - resolve category url from current url.
                    categoryUrl = window.location.href.split('?')[0];
                    if (alternativeReferrer && alternativeReferrer.length > categoryUrl.length) {
                        categoryUrl = alternativeReferrer;
                        if (categoryUrl.indexOf('?') > 0) {
                            categoryUrl = categoryUrl.substr(0, categoryUrl.indexOf('?'));
                        }
                    } else {
                        categoryUrl = categoryUrl.substring(0, categoryUrl.lastIndexOf('/')) +
                            this.options.categoryUrlSuffix;
                    }
                } else {
                    // In other case - try to resolve it from referrer (without parameters).
                    categoryUrl = document.referrer;

                    if (categoryUrl.indexOf('?') > 0) {
                        categoryUrl = categoryUrl.substr(0, categoryUrl.indexOf('?'));
                    }
                }

                return categoryUrl;
            }

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.