Magento 2 store categories make it easy for the visitors to find the exact desired product quickly.
Here’s the programmatic solution to get all category URLs in Magento 2. With this solution, the admin can get the list of all categories URLs in the store and then use it in multiple ways according to the business requirements.
For example, you want to implement HTML sitemap in Magento 2 store. HTML sitemap is sort of a blueprint of the online store. It makes navigation easy. The admin can also use HTML sitemap to keep the track of all the URLs in the Magento 2 store. Using the below code, one can list the category URLs in the HTML sitemap.
Also, when the Magento 2 store gradually expands, the admin may want a handy list of category URLs while adding new or updating the existing categories.
In all such scenarios, use the below solution to get all categories URLs in Magento 2.
Steps to Get All Category URLs in Magento 2
1. Use the below code in registration.php at app/code/Vendor/Module
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Vendor_Module',
__DIR__
);
2. Create module.xml at app/code/Vendor/Module/etc/ and paste the below code.
<?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_Module" setup_version="1.0.0">
</module>
</config>
3. Create CategoryPageUrls.php at app/code/Vendor/Module/Helper/ and use the below code.
<?php namespace Vendor\Module\Helper; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; class CategoryPageUrls extends AbstractHelper { const CATEGORY_URL_SUFFIX = 'catalog/seo/category_url_suffix'; /** * @var CategoryCollectionFactory */ private $categoryCollectionFactory; public function __construct(Context $context, CategoryCollectionFactory $categoryCollectionFactory) { $this->categoryCollectionFactory = $categoryCollectionFactory;
parent::__construct($context);
}
public function getCategoryUrls()
{
$categoryUrls = [];
$categories = $this->categoryCollectionFactory->create();
$categories->addAttributeToSelect('url_path');
foreach ($categories as $category) {
if (!is_null($category->getData('url_path'))) {
$categoryUrls[] = rtrim($this->getUrl($category->getData('url_path')), '/') .
$this->getConfigData(self::CATEGORY_URL_SUFFIX);
}
}
return $categoryUrls;
}
public function getConfigData($path, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = null)
{
return $this->scopeConfig->getValue($path, $scope, $scopeId);
}
}
That’s it.
Do not forget to share the solution with Magento Community via social media.
Thank You.
Related Posts: