I have created a custom script that'll generate a sitemap for the first level of child categories. Hope it'll help someone.
Download 'SitemapGenerator.php' from https://github.com/icamys/php-sitemap-generator
set_time_limit(18000);
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
require_once 'SitemapGenerator.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productCollection = $obj->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryCollection = $obj->get('\Magento\Catalog\Model\CategoryFactory');
$sitemap_path = getcwd() .'/sitemaps/';
// Get First Level of Childerns
$categoryIds = Array('3');
foreach ($categoryIds as $categoryId) {
$_category = $categoryCollection->create();
$category = $_category->load($categoryId);
$categories = $category->getCollection()
->addIsActiveFilter()
->addOrderField('name')
->addIdFilter($category->getChildren());
foreach ($categories as $category) {
$name = $category->getName();
$name = preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($name));
$file = $sitemap_path.$name.'.xml';
if(file_exists($file))
{
@unlink($file);
}
$categoryProducts = $productCollection->create();
$categoryProducts->addAttributeToSelect('*');
$categoryProducts->addCategoriesFilter(['in' => [$category->getId()] ]);
$categoryProducts->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$categoryProducts->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
if(count($categoryProducts))
{
$generator = new \Icamys\SitemapGenerator\SitemapGenerator('');
$generator->createGZipFile = false;
$generator->maxURLsPerSitemap = 50000;
$generator->sitemapFileName = $file;
foreach ($categoryProducts as $product) {
$generator->addUrl($product->getProductUrl(), new DateTime(), 'weekly', '0.5');
}
$generator->createSitemap();
$generator->writeSitemap();
}
}
}