Skip to content

Magento 2.4 – Programmatically Created Categories in Multi-Store Collide

I have a Magento 2.4.3 multi-store and I am currently creating categories programmatically, with the following code:

$category = $objectManager->create('MagentoCatalogModelCategory',
                        ['data' => 
                               ["name"            => $refCat['name'],
                                "is_active"       => $refCat['active'],
                                "include_in_menu" => $refCat['menu'],
                                "parent_id"       => $parentID,
                                "store_id"        => $refCat['store_id']]]);
$category->setCustomAttributes(["display_mode"               => "PRODUCTS",
                                "custom_use_parent_settings" => true,
                                "is_anchor"                  => "1"]);

$repository = $objectManager->get(MagentoCatalogApiCategoryRepositoryInterface::class);
$repository->save($category);

Unfortunately, I am unable create categories with the same name, example “Brands”, even if they are assigned to different store ids, as I get the following error: Could not save category: URL key for specified store already exists.

After reviewing the URL_Rewrite table, I found that the entries for any store created using the above method have a store_id value of 1, regardless of what value was passed assigned when the category was created.

What am I missing?