Skip to content

Instantly share code, notes, and snippets.

@ircykk
Created October 23, 2021 14:05
Show Gist options
  • Save ircykk/e7f640bae1aba167fdd2317e59357a16 to your computer and use it in GitHub Desktop.
Save ircykk/e7f640bae1aba167fdd2317e59357a16 to your computer and use it in GitHub Desktop.
Fix product categories tree to display subcategory products in parent category
<?php
// fix product categories tree to display subcategory products in parent category
require dirname(__FILE__).'/config/config.inc.php';
$limit = 100;
$offset = 0;
do {
$sql = new DbQuery();
$sql->select('p.id_product, p.id_category_default');
$sql->from('product', 'p');
$sql->limit($limit, $offset);
$products = Db::getInstance()->executeS($sql);
foreach ($products as $productRow) {
$product = new Product($productRow['id_product']);
$categoriesIds = [];
foreach ($product->getCategories() as $categoryId) {
// add categories
$categoriesIds[] = $categoryId;
// add parents of categories
$category = new Category($categoryId);
$parents = $category->getParentsCategories();
$parentsIds = array_column($parents, 'id_category');
$categoriesIds = array_merge($categoriesIds, $parentsIds);
}
$categoriesIds = array_unique($categoriesIds);
$product->addToCategories($categoriesIds);
echo '['.$offset.'] Product: ' . $product->id . ', categories: ' . implode(',', $categoriesIds) . PHP_EOL;
}
$offset += $limit;
} while (count($products));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment