How To

Magento 2: How to Skip Categories from Breadcrumbs on the Category Page

Hello Magento Friends,

In today’s blog, we will learn about How to Skip Categories from Breadcrumbs on the Category Page in Magento 2.

Breadcrumbs in Magento 2 serve as a navigational aid for users to understand their current location within the site’s hierarchy. They are particularly important on category pages, where users often want to move up the category tree to view similar products.

Magento 2 Breadcrumbs Extension can help you to easily show breadcrumbs on product pages and improve the navigational experience of customers.

By default, Magento 2 includes all parent categories in the breadcrumb path, which can sometimes create a lengthy and less user-friendly breadcrumb trail. In this blog post, we will discuss how to modify the Magento 2 breadcrumb functionality to skip certain categories and create a cleaner and more concise breadcrumb trail for users.

Why Skip Categories in Breadcrumbs?

Before we delve into the technical aspect of how to skip categories in breadcrumbs, it’s essential to understand why this might be necessary. Here are a few reasons why you might consider skipping certain categories:

  • Relevancy: Sometimes, including all parent categories in the breadcrumb trail can dilute the relevancy of the breadcrumbs, especially if the skipped category is not directly related to the product or content being viewed.
  • User Experience: Long breadcrumb trails can be overwhelming and might not provide the best user experience, especially on mobile devices or smaller screens.
  • SEO Considerations: Breadcrumb trails are essential for search engines to understand the structure and hierarchy of your site. By skipping certain categories, you can help search engines focus on the most relevant aspects of your site.

Steps to Skip Categories from Breadcrumbs on the Category Page in Magento 2:

Step 1: Create the registration.php file inside the Extension folder.

app\code\Vendor\Extension\

And add the code as follows

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Extension',
    __DIR__
);

Step 2: Now, create module.xml file inside etc folder.

app\code\Vendor\Extension\etc\

Then include the code as mentioned below

<?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="Vendor_Extension" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
        </module>
</config>

Step 3: Then create CustomAttributes.php file inside the Data folder.

app\code\Vendor\Extension\Setup\Patch\Data

And add the following code snippet

<?php
namespace Vendor\Extension\Setup\Patch\Data;

use Magento\Eav\Setup\EavSetup;
use Magento\Catalog\Model\Product;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;

class CustomAttributes implements DataPatchInterface
{
     /** @var ModuleDataSetupInterface */    private $moduleDataSetup;

    /** @var EavSetupFactory */    private $eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */    public function apply()
    {
        /** @var EavSetup $eavSetup */        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->addAttribute(
            Category::ENTITY,
            'breadcrumb',
           [
                'type' => 'text',
                'label' => 'Breadcrumb',
                'input' => 'text',
                'global' => Attribute::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'is_used_in_grid' => false,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false,
                'used_in_product_listing' => true,
                'visible_on_front' => true,
                'group' => 'Custom Design',
                'note' => 'enter category id with comma-separated.(i.e : 3,4,5)'
            ]
        );
 
    }

    /**
     * {@inheritdoc}
     */    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */    public function getAliases()
    {
        return [];
    }
}

Step 4: Then create di.xml file inside frontend folder.

app\code\Vendor\Extension\etc\frontend\

And add the following piece of code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Breadcrumbs" type="Vendor\Extension\Block\Breadcrumbs" />
</config>

Step 5: After that, create Breadcrumbs.php file inside Block folder.

app\code\Vendor\Extension\Block\

And add the below-mentioned code

<?php
namespace Vendor\Extension\Block;

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

class Breadcrumbs extends \Magento\Framework\View\Element\Template
{
    /**
     * Catalog data
     *
     * @var Data
     */    protected $_catalogData = null;
    protected $_registry;

    /**
     * @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);
    }

    /**
     * Retrieve HTML title value separator (with space)
     *
     * @param null|string|bool|int|Store $store
     * @return string
     */    public function getTitleSeparator($store = null)
    {
        $separator = (string)$this->_scopeConfig->getValue(
            'catalog/seo/title_separator',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $store
        );
        return ' ' . $separator . ' ';
    }

    /**
     * Preparing layout
     *
     * @return \Magento\Catalog\Block\Breadcrumbs
     */    protected function _prepareLayout()
    {
        $category = $this->_registry->registry('current_category');

        $array = array();
        if($category->getBreadcrumb()){
            $array = explode(",",$category->getBreadcrumb());
        }
        
        if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {
            $breadcrumbsBlock->addCrumb(
                'home',
                [
                    'label' => __('Home'),
                    'title' => __('Go to Home Page'),
                    'link' => $this->_storeManager->getStore()->getBaseUrl()
                ]
            );
            
            $title = [];
            $path = $this->_catalogData->getBreadcrumbPath();
        
            foreach ($path as $name => $breadcrumb) {
                $category_id = str_replace('category', '', $name);
                if (!in_array($category_id, $array)){
                    $breadcrumbsBlock->addCrumb($name, $breadcrumb);
                    $title[] = $breadcrumb['label'];    
                }
            }

            $this->pageConfig->getTitle()->set(join($this->getTitleSeparator(), array_reverse($title)));
        }
        return parent::_prepareLayout();
    }
}

Step 6: Lastly, create category_form.xml file inside ui_component folder.

app\code\Vendor\Extension\view\adminhtml\ui_component

And add the code as below

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="design">
        <field name="breadcrumb">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">52</item>
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="label" xsi:type="string" translate="true">Breadcrumb</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

Result:

In Magento 2, by default the Breadcrumbs are shown as follows

After implementing the above steps, you can easily skip some categories from breadcrumbs by adding the category ID from Magento admin as shown below

Look into the frontend of your Magento 2 store. Those categories will not be visible on the breadcrumbs.

Conclusion:

By following these steps, you can create a more relevant and user-friendly breadcrumb trail that enhances the overall browsing experience on your Magento 2 store.

Relevant Article – 

How to Show/Remove Breadcrumbs to CMS Pages in Magento 2

If you have any doubt, share it with me through the comment section.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Why Your Business Needs a SaaS/E-commerce Marketing Agency?

In today’s era, having a solid online presence and effective marketing strategies are vital factors…

5 hours ago

Handling File Uploads in a Remix Application

In this blog, I will explain about handling file uploads in Shopify Remix App. File…

5 hours ago

Upgrade Your E-commerce Store with Magento 2 Hyvä Theme

Magento 2 Hyvä Theme is quickly becoming a popular choice among e-commerce businesses for its…

1 day ago

A Complete Guide of Hyvä Themes

In the rapidly evolving world of e-commerce, the success of an online store greatly hinges…

1 day ago

Magento 2: How to Add Custom Button to Download Custom Created PDF Programmatically in Admin Sales Order View

Hello Magento Friends, Ever wanted to provide admins with a quick way to download custom…

1 day ago

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

6 days ago