Skip to content

Instantly share code, notes, and snippets.

@satishgumudavelli
Last active July 6, 2022 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satishgumudavelli/62c90e7e656daf173714746570b80445 to your computer and use it in GitHub Desktop.
Save satishgumudavelli/62c90e7e656daf173714746570b80445 to your computer and use it in GitHub Desktop.
Delete media gallary by sku
<?php
/* Need to add this script and csv in var/shell folder */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
set_time_limit(0);
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\ResourceModel\AttributeValue;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ObjectManager;
require __DIR__ . '/../../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$resourceConnection = $obj->get('Magento\Framework\App\ResourceConnection');
$connection = $resourceConnection->getConnection();
$mediaConfig = $obj->get('Magento\Catalog\Model\Product\Media\Config');
$filesystem = $obj->get('Magento\Framework\Filesystem');
$directory = $filesystem->getDirectoryRead('media');
$header = [];
$csvFile = file(dirname(realpath(__FILE__)) . '/removemediaimages.csv');
$skus = [];
$cnt = 0;
foreach ($csvFile as $line) {
$row = str_getcsv($line);
if (!$header) {
$header = $row;
continue;
}
$skus[] = trim($row[0]);
$cnt++;
/*if ($cnt > 5) {
break;
}*/
}
$eavAttributeTable = $resourceConnection->getTableName('eav_attribute');
$catalogProductEntityTable = $resourceConnection->getTableName('catalog_product_entity');
$catalogProductEntityMediaGalleryValueToEntityTable = $resourceConnection->getTableName('catalog_product_entity_media_gallery_value_to_entity');
$catalogProductEntityMediaGalleryTable = $resourceConnection->getTableName('catalog_product_entity_media_gallery');
$catalogProductEntityMediaGalleryValueTable = $resourceConnection->getTableName('catalog_product_entity_media_gallery_value');
$entityId = $connection->tableColumnExists($catalogProductEntityTable, 'row_id') ? 'row_id' : 'entity_id';;
$mediaGallaryAttrQuery = $connection->select()
->from(
['ea' => $eavAttributeTable],
['attribute_id']
)
->where('attribute_code = ?', 'media_gallery')
->where('entity_type_id = ?', 4);
$mediaGallaryAttrId = $connection->fetchOne($mediaGallaryAttrQuery);
$inline1Query = $connection->select()
->from(
['cpe' => $catalogProductEntityTable],
[$entityId]
)
->where('sku in (?)', $skus);
$inlineQuery = $connection->select()
->from(
['cpemgvte' => $catalogProductEntityMediaGalleryValueToEntityTable],
['value_id']
)
->where("$entityId in (?)", $inline1Query)
->where('attribute_id in (?)', [$mediaGallaryAttrId]);
$finalQuery = $connection->select()
->from(
['cpemg' => $catalogProductEntityMediaGalleryTable],
['value_id', 'file' => 'value']
)->where('value_id in (?)', $inlineQuery);
$images = $connection->fetchAll($finalQuery);
$attributeValue = ObjectManager::getInstance()->get(AttributeValue::class);
$productCollection = ObjectManager::getInstance()->get(\Magento\Catalog\Model\Product::class)->getCollection();
foreach ($images as $image) {
$imagePath = $directory->getAbsolutePath($mediaConfig->getMediaPath($image['file']));
if (file_exists($imagePath)) {
unlink($imagePath);
}
$whereConditions = [
$connection->quoteInto('value_id = ?', $image['value_id']),
$connection->quoteInto('attribute_id = ?', $mediaGallaryAttrId),
];
$connection->delete($catalogProductEntityMediaGalleryTable, $whereConditions);
echo $imagePath . " deleted .\n";
}
$allProductIds = $connection->fetchCol($inline1Query);
$whereConditions = [
$connection->quoteInto("$entityId in (?)", $allProductIds),
];
$connection->delete($catalogProductEntityMediaGalleryValueToEntityTable, $whereConditions);
$connection->delete($catalogProductEntityMediaGalleryValueTable, $whereConditions);
$mediaAttributes = ['image', 'small_image', 'thumbnail'];
$productCollection
->addFieldToFilter($entityId, ['in' => $allProductIds])
->addAttributeToSelect($mediaAttributes, 'left')
->addAttributeToFilter(
[
['attribute' => 'image', 'is' => new \Zend_Db_Expr('not null')],
['attribute' => 'small_image', 'is' => new \Zend_Db_Expr('not null')],
['attribute' => 'thumbnail', 'is' => new \Zend_Db_Expr('not null')]
]
);
foreach ($productCollection->getData() as $_product) {
$product = ObjectManager::getInstance()->create(\Magento\Catalog\Model\Product::class)->load($_product['entity_id']);
$productResource = $product->getResource();
$storeIds[] = 0;
$storeIds = array_merge($storeIds, $product->getStoreIds());
echo $product->getSku() . " \n";
foreach ($mediaAttributes as $mediaAttribute) {
foreach ($storeIds as $storeId) {
$product->setStoreId($storeId);
$product->setData($mediaAttribute, null);
$productResource->saveAttribute($product, $mediaAttribute);
}
}
}
sku
SKU-1
SKU-2
SKU-3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment