Created
November 12, 2019 16:04
-
-
Save gukandrew/69337bf89db8704be2485ff62b097942 to your computer and use it in GitHub Desktop.
Force resave all products with custom options for store Magento 2 php script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Magento\Framework\App\Bootstrap; | |
include 'app/bootstrap.php'; | |
// config | |
$pageSize = 100; | |
// config end | |
$bootstrap = Bootstrap::create(BP, $_SERVER); | |
$objectManager = $bootstrap->getObjectManager(); | |
$state = $objectManager->get('Magento\Framework\App\State'); | |
$state->setAreaCode('adminhtml'); | |
if (count($argv) <= 1) { | |
die("Store ID(s) are missing! Please pass as first argument! E.g `php ./resaveall.php '1,2,3,4,5'`\n\n"); | |
} | |
$storeIds = explode(',', $argv[1]); | |
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); | |
foreach ($storeIds as $storeId) { | |
$storeId = (int) $storeId; | |
$productsTotal = $productCollectionFactory->create()->addStoreFilter($storeId)->count(); | |
echo "Store ID $storeId has $productsTotal products! Resaving those that have custom options!\n"; | |
echo "===================================\n"; | |
$pageNumber = (int) ($productsTotal / $pageSize); | |
$productcollection = $productCollectionFactory->create()->addStoreFilter($storeId)->addAttributeToSelect('*'); | |
$savedNumber = 0; | |
for ($i=1; $i <= $pageNumber; $i++) { | |
$productcollection->setPage($i, $pageSize); | |
foreach ($productcollection as $product) { | |
$customOptions = $objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product); | |
$hasOptions = false; | |
foreach($customOptions as $option) { | |
$values = $option->getData(); | |
if (!empty($values)) { | |
$hasOptions = true; // has custom options (incl. mageworx options) | |
break; | |
} | |
} | |
if (!$hasOptions) { | |
continue; | |
} | |
$productId = $product->getId(); | |
$product = $objectManager->create('Magento\Catalog\Model\Product'); | |
$product->load($productId); | |
$product->save(); | |
$savedNumber++; | |
echo "Saved product $productId\n"; | |
} | |
$productcollection->clear(); | |
} | |
echo "===================================\n"; | |
echo "Store $storeId - DONE! Saved $savedNumber products wit custom options!\n"; | |
echo "===================================\n"; | |
} | |
echo "All DONE!\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment