I am working on duplicate category, In my controller file, I am able to duplicate the category but I need to assign the same products to the newly created category from the old one.

i.e. I have the category name "Abc" has 10 products and 2 of them are In-stock / out of stock / disable, now I duplicate the category with and the new name is "Xyz". I want to assign all 10 products into "Xyz".

How could I achieve this functionality?

class DuplicateCategory extends \Magento\Backend\App\Action {
protected $_categoryFactory;    
public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
    $this->_categoryFactory = $categoryFactory;

$parentCategoryObj = $this->_categoryFactory->create()->load(2);
$duplicateCategoryObj = $this->_categoryFactory->create()->load(8);
$catagoryObject = $this->_categoryFactory->create();

$categoryName = $duplicateCategoryObj->getName();
$categoryUrlKey = strtolower($this->getCategoryUrlKey($categoryName));

  • Can you please upload your code logic which you have done? Jul 19, 2019 at 6:35
  • Use this extension instead if you are OK with it. It will make your life easier with duplicating categories. Jan 16, 2020 at 9:59

1 Answer 1


When possible I would try to use APIs for interacting with the Magento core.

Consider using:

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterfaceFactory;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\CategoryInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface

The duplicate product assignment might look something like

$categoryProductLinks = $this->categoryLinkManagement

/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $categoryProductLink */
foreach ($categoryProductLinks as $categoryProductLink) {
    $product = $this->productRepository->get($categoryProductLink->getSku());
    $categoryIds = $product->getCategoryIds();
    array_push($categoryIds, $newCategory->getId());
         ->assignProductToCategories($product->getSku(), $categoryIds);


  • Above is just an example of an idea and not tested code.
  • While productRepository->get returns \Magento\Catalog\Api\Data\ProductInterface the underlying object \Magento\Catalog\Model\Product has getCategoryIds()

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .