Skip to content

Instantly share code, notes, and snippets.

@vinaysikarwar
Created December 14, 2022 10:31
Show Gist options
  • Save vinaysikarwar/9c4fd0213bf452dc71bf2ad694d6966e to your computer and use it in GitHub Desktop.
Save vinaysikarwar/9c4fd0213bf452dc71bf2ad694d6966e to your computer and use it in GitHub Desktop.
Update child product categories associated with Configurable product
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', -1);
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require __DIR__ .'/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$registry = $objectManager->get('Magento\Framework\Registry');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$count = 1;
foreach ($collection as $product) {
if($product->getTypeId() == "configurable"){
echo "<b>".$count++ .".</b> Updating child products for config product id <b>".$product->getId()."</b>";
$categoryIds = $product->getCategoryIds();
$_childrens = $product->getTypeInstance()->getUsedProductIds($product);
echo " => Updating child Ids: <b>". implode(",",$_childrens)."</b>";
foreach($_childrens as $child){
$_product = $objectManager->get("\Magento\Catalog\Model\Product");
$_product = $_product->load($child);
$childCategoryIds = $_product->getCategoryIds();
$sku = $_product->getSku();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);
}
echo "<br/>";
}
}
echo "All Child Product categories updated successfully.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment