0

Can anyone tell me how can i fetch all the Simple SKU's and remove all the categories from those SKU via PHP script in magento 2.4.4.

1 Answer 1

0

To achieve that, create a new PHP file in your Magento directory which is the same level as app, lib, pub ... with the following content:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '5G');

use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$collectionFactory = $objectManager->create(Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class);
/** @var Collection $collection */
$collection = $collectionFactory->create();
$collection->addAttributeToFilter('type_id', ['eq' => Type::TYPE_SIMPLE])->load();

foreach ($collection as $product) {
    $product->setData('category_ids', null)->save();
}

For example, you set the file name removeAllCategoriesFromSimpleProducts.php, to execute the script, you should run the following command from the SSH terminal:

php removeAllCategoriesFromSimpleProducts.php
7
  • Hello, i am getting error when i run this file. Feb 2, 2023 at 6:55
  • PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'tommy-hilfiger-sunglasses-th-1556-s-08a-ir-black-gray-1' for key 'URL_REWRITE_REQUEST_PATH_STORE_ID' in /var/www/vhosts/stagingdiscountedsunglasses/htdocs/vendor/magento/framework/DB/Statement/Pdo/Mysql.php:91 Stack trace: Feb 2, 2023 at 6:56
  • That means your URL Rewrites data (for products) has problem(s). To fix this issue, from admin, go to Marketing > URL Rewrites, and filter by the Request Path with the key in the error, you will see some duplicate records and you should resolve it. Or if you see many products have URL Rewrites duplicates, you should use an extension to resolve the issue: github.com/elgentos/magento2-regenerate-catalog-urls
    – Tu Van
    Feb 2, 2023 at 7:20
  • i am having issue with suppose this url key " bvlgari-eyeglasses-bv4165-504-dark-havana-women-1" but i see only one entry in url rewrites prnt.sc/TKUNFF1veAIL . So there is no duplicate entry here Feb 2, 2023 at 8:21
  • There are some issues with your URL Rewrites, please use the extension I mentioned above to re-generate URL Rewrites then run my code. I've tested my code before sharing the code (with Magento default with sample data and the site is multiple stores), so it should work as expected.
    – Tu Van
    Feb 2, 2023 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.