Hello Magento Friends,
In this blog, we will learn about How to Remove Parent Categories from Subcategory URLs in Magento 2.
URLs matter in ensuring SEO performance and improving user experience. In Magento 2, by default, a subcategory URL contains the parent category. As a case in point, if you have a parent category named “Electronics” and a subcategory named “Mobile Phones,” the URL may look like this:
https://example.com/electronics/mobile-phones
While this makes sense, it can be longer and less appealing for both SEO and usability purposes. In this blog, we will teach you how to remove categories from the subcategory URLs that need to be shorter and cleaner.
Steps to Remove Parent Categories from Subcategory URLs in Magento 2:
Step 1: Create a “di.xml” file inside our extension at the following path.
app\code\Vendor\Extension\etc\di.xml
Now add the code as follows
<?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\CatalogUrlRewrite\Model\CategoryUrlPathGenerator"
type="Vendor\Extension\Model\CategoryUrlPathGenerator"/>
</config>
Step 2: Create the “CategoryUrlPathGenerator.php” file inside our extension at the following path.
app/code/Vendor/Extension/Model/CategoryUrlPathGenerator.php
Now add the below mentioned code
<?php
declare(strict_types=1);
namespace Vendor\Extension\Model;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator as Magento_CategoryUrlPathGenerator;
use Magento\Framework\Model\AbstractModel;
class CategoryUrlPathGenerator extends Magento_CategoryUrlPathGenerator
{
/**
* @param CategoryInterface|AbstractModel $category
* @param null $parentCategory
* @return string|null
*/
public function getUrlPath($category, $parentCategory = null)
{
if (in_array($category->getParentId(), [Category::ROOT_CATEGORY_ID, Category::TREE_ROOT_ID])) {
return '';
}
$path = $category->getUrlPath();
if ($path !== null && !$category->dataHasChangedFor('url_key') && !$category->dataHasChangedFor('parent_id')) {
return $path;
}
$path = $category->getUrlKey();
if ($path === false) {
return $category->getUrlPath();
}
return $path;
}ss
}
Conclusion:
By removing parent categories from subcategory URLs, you can create a cleaner, more user-friendly URL structure for your Magento 2 store. Follow the steps above, and you’ll have shorter, cleaner URLs in no time!
If you have any questions or need assistance with your Magento 2 store, feel free to reach out to us.
Happy Coding!