set image to category programmatically in Magento - image

I try to add a category in magento by this code:
$_cat = new Mage_Catalog_Model_Category();
$_cat->setName($nom);
$_cat->setUrlKey($nom);
$_cat->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$_cat->setPath($parentCategory->getPath());
$mediaAttribute = array ('thumbnail');
$_cat->addImageToMediaGallery($other_file, $mediaAttribute, true, false);
$_cat->save();
its works, but the image is not inserted, I need to know what is the correct code to insert the category image programmatically,
Thanks u.

ok I solved it , to add additionnel datas write :
$data['display_mode'] = 'PRODUCTS_AND_PAGE';
$data['page_layout'] = 'one_column';
$data['thumbnail'] = $path; // path to your image
$_cat->addData($data);
then put your image in YOUR_MAGENTO/media/catalog/category/NAME_OF_IMAGE.jpg
Cheers.

Here is a working example:
$newCategory = Mage::getModel('catalog/category');
$newCategory->setName('Category name');
$newCategory->setUrlKey('category-name');
$newCategory->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$newCategory->setPath($parentCategory->getPath());
$newCategory->setImage('file_name.jpg');
$newCategory->save();
Make sure your category image 'file_name.jpg' is uploaded to media/catalog/category/file_name.jpg
BTW, any answer mentioning "addImageToMediaGallery" is wrong. This method only exist for product, not for category.
Also the correct attribute name for category is "image" not "thumbnail".

You could have also done to make it look cleaner and more readable:
$parentCategory = Mage::getModel('catalog/category')->load(2);
$newCategory = Mage::getModel('catalog/category');
$newCategory->setName($nom);
$newCategory->setUrlKey($nom);
$newCategory->setIsActive(1);
$newCategory->setPath($parentCategory->getPath());
$newCategory->addImageToMediaGallery($other_file, array ('thumbnail'), true, false);
$newCategory->setDisplayMode('PRODUCTS_AND_PAGE');
$newCategory->setPageLayout('one_column');
$newCategory->setThumbnail($path); // path to your image
$newCategory->save();
What do you think?

ElGabbu, in your code i get this error :
PHP Fatal error: Uncaught exception 'Varien_Exception' with message 'Invalid method Mage_Catalog_Model_Category::addImageToMedia Gallery(Array
(
[0] => image.jpg
[1] => Array
(
[0] => thumbnail
)
[2] => 1
[3] =>
)
)' in /home/www/magento/lib/Varien/Object.php:569
that my code who worked for me :
$_cat = new Mage_Catalog_Model_Category();
$_cat->setName($nom);
$_cat->setUrlKey($nom);
$_cat->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$_cat->setPath($parentCategory->getPath());
$_cat->setIsAnchor(1);
$data['display_mode'] = 'PRODUCTS_AND_PAGE';
$data['page_layout'] = 'one_column';
$data['thumbnail'] = $path;
$_cat->addData($data);
$_cat->save();

I use the following snipped based on Mage_Catalog_Model_Product_Attribute_Backend_Media and Mage_Catalog_Model_Category_Attribute_Backend_Image to copy the image from external path to the thumbnail property including a _1 suffix if needed.
$attr = 'thumbnail';
$new_file = ...; // absolute path to your file
$category = ...; // your category model
$path = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
if (md5_file($new_file) != md5_file($path.$category->getData($attr)) {
$ioObject = new Varien_Io_File();
try {
$ioObject->open(array('path'=>$path));
} catch (Exception $e) {
$ioObject->mkdir($path, 0777, true);
$ioObject->open(array('path'=>$path));
}
$destFile = $path . Mage_Core_Model_File_Uploader::getNewFileName($path . basename($new_file));
$ioObject->cp($new_file, $destFile);
$category->setData($attr, basename($destFile));
}

Related

Magento: How to exclude image from gallery programmatically?

I am creating products and images programmatically. The only thing that is not working is the "exclude from gallery" feature.
See http://snag.gy/QGhPg.jpg for details.
How would I set that in the code? My current code looks like that:
$product->addImageToMediaGallery($myImage, array('image','thumbnail','small_image'), false, false);
The flag is called disabled I think, not sure though.
Thanks!
For example, disable all images for a product
$product = Mage::getModel('catalog/product')->load(12345);
$images = $product->getMediaGalleryImages();
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$mediaGalleryAttribute = $attributes['media_gallery'];
foreach ($images as $image) {
$mediaGalleryAttribute->getBackend()->updateImage($product, $image['file'], array('exclude' => true));
}
$product->save();
Try to use:
$product->addImageToMediaGallery($myImage, array('image','thumbnail','small_image'), false, true);
The last parameter should be set to true to exclude the image from gallery.
See: app/code/core/Mage/Catalog/Model/Product.php.
Try below code..first save product and insert image
$productid=10; // Product id of that product which image you want to update
//for remove existing Images
$loadpro=Mage::getModel('catalog/product')->load($productid);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApiItems = $mediaApi->items($loadpro->getId());
foreach($mediaApiItems as $item) {
$datatemp=$mediaApi->remove($loadpro->getId(), $item['file']);
}
$loadpro->save(); //before adding need to save product
//for add new images
$loadpro=Mage::getModel('catalog/product')->load($loadpro->getId());
$loadpro->addImageToMediaGallery($loadpro, array ('image','small_image','thumbnail'), true, false);
$mediaArray = array(
'thumbnail' => $oscProduct['products_image'],
'small_image' => $oscProduct['products_mediumimage'],
'image' => $oscProduct['products_largeimage'],
);
// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/';
foreach ( $mediaArray as $imageType => $fileName ) {
$filePath = $importDir . $fileName;
if ( file_exists($filePath) ) {
try {
$product->addImageToMediaGallery($filePath, $imageType, false);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
}
}
Note: $imageType is not an array, as your counterpart is.
Edit: You only want one image, and to set it as each type. After you save the product with $product->save(), try something like the following, assuming you have set the image type already:
$product->setThumbnail($product->getImage());
$product->setSmallImage($product->getImage());
$product->save();

set a chosen image-file-input as a featured image from wp frontend

SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}

Render a Joomla 2.5 Menu Module with some PHP

Trying to use this code to render a menu module on a custom template
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule( 'menu' );
$attribs = array('style' => 'mainnav');
$module->params = "menutype=" .$mainmenu ."\nshowAllChildren=1";
echo JModuleHelper::renderModule($module, $attribs);
The menu only works if I have another menu module published, so I am sure this only needs a line of code to make it work without having to publish a menu module.
The menu exists, the module for this menu does not exist, I am trying to create it with this code.
Please help.
The code works fine I just had a small correction to make:
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule( 'mod_menu' );
$attribs = array('style' => 'mainnav');
$module->params = "menutype=" .$mainmenu ."\nshowAllChildren=1";
echo JModuleHelper::renderModule($module, $attribs);
on the second line, the call should be to "mod_menu" and not just "menu", and this makes the code to work perfect :)
Why don't just use the include module?
<jdoc:include type="modules" name="mainnav" style="mainnav" />
This will allow you to publish whatever module you wan't in that position.
Otherwise the getModule function works like this:
JModuleHelper::getModule( 'position', 'title' );
According to the Joomla! API so you need to pass both parameters.
i use this code to render other module by id
$mod_id = $params->get('mod_id');
if ($type == 'logout' && $mod_id != ''){
$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('module');
$db =& JFactory::getDBO();
if ($jVersion=='1.5') {
$query = 'SELECT id, title, module, position, params'
. ' FROM #__modules AS m'
. ' WHERE id='.intval($mod_id);
} else {
$query = 'SELECT id, title, module, position, content, showtitle, params'
. ' FROM #__modules AS m'
. ' WHERE m.id = '.intval($mod_id);
}
$db->setQuery( $query );
if ($mod = $db->loadObject()){
$file = $mod->module;
$custom = substr( $file, 0, 4 ) == 'mod_' ? 0 : 1;
$modu->user = $custom;
// CHECK: custom module name is given by the title field, otherwise it's just 'om' ??
$mod->name = $custom ? $mod->title : substr( $file, 4 );
$mod->style = null;
$mod->position = strtolower($mod->position);
echo $renderer->render($mod, array());
}
}
use this, 100%, render modules at this position.
<?php
$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('modules');
$options = array('style' => 'xhtml');
$position = 'article-banners';
echo $renderer->render($position, $options, null);
?>
$position refer to module position, may be more than one...
$style - none, rounded, xhtml...

Magento programmatically remove product images

This must be a such a simple programming task that I absolutely cannot find any information about it on the net. Basically, I'm trying to DELETE product images. I want to delete all images from a product's media gallery. Can I do this without wading through a million lines of code for such a simple task?
Please note that I've already tried this:
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
$galleryData = $product->getMediaGallery();//this returns NULL
foreach($galleryData['images'] as $image){
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
This absolutely does not work. I'm trying to delete images during an import so that I do not keep accruing duplicates. Any help would be greatly appreciated.
Okay, this is how I finally fixed my problem.
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item)
$mediaApi->remove($product->getId(), $item['file']);
}
This is the link that finally set my head straight: http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media
Too bad it's not as simple as $product->getImages(), eh?
In Magento 1.7.0.2 I use this code for remove all images from a product gallery:
//deleting
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
With code from Davids Tay answer, I got the error:
Fatal error: Uncaught exception ‘Mage_Eav_Model_Entity_Attribute_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (base_xxx.catalog_product_entity_media_gallery_value, CONSTRAINT FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID FOREIGN KEY (value_id) REFERENCES `catalog_prod)’
To remove all images from a product gallery:
$product = Mage::getModel('catalog/product')->load($id);
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());
$product->save();
During deleting of images I found one interesting thing. When you try this code:
$galleryData = $product->getMediaGallery(); //this returns NULL
Media gallery object depends on how your product was created, if:
$product = Mage::getModel('catalog/product')->loadByAttr('sku', $sku);
then media gallery will be empty, if:
$product = Mage::getModel('catalog/product')->load($id);
then media gallery is object and you can use this object to delete images from db.
To delete images from file system you have to add such code:
#unlink(Mage::getBaseDir('media') . '\catalog\product\' . $image['file']);
but if you want to change image and name it like previous image (image1.png replace with image1.png) in this case you will have browser caching issue.
Also you can try to load media gallery for product:
$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);
This is the code I finally decided to use for this task.
protected function _removeMediaGalleryImages(Mage_Catalog_Model_Product $product)
{
$mediaGalleryData = $product->getMediaGallery();
if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
return;
}
$toDelete = array();
foreach ($mediaGalleryData['images'] as $image) {
$toDelete[] = $image['value_id'];
}
Mage::getResourceModel('catalog/product_attribute_backend_media')->deleteGallery($toDelete);
}
Hopefully this answer isn't unwelcome, as it's technically not a solution achieved via Magento programming as you ask, but I have successfully purged all gallery images myself for the same purpose simply by truncating the relevant tables in Magento 1.4.2.0 (I believe it's the same table structure in 1.5 as well).
TRUNCATE TABLE `catalog_product_entity_media_gallery`
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`
Then follow up by removing all the image files within the /media/catalog/product directory.
I did look for a way to do this programmatically myself, but found this much more efficient and have experienced no negative side effects.
Just use this code to create .php file and place it to root folder of magento.
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
//->addAttributeToFilter('entity_id', array('gt' => 14000));
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
foreach($products as $product) {
$prodID = $product->getId();
$_product = Mage::getModel('catalog/product')->load($prodID);
$items = $mediaApi->items($_product->getId());
foreach($items as $item) {
$mediaApi->remove($_product->getId(), $item['file']);
}
}
?>
What About this
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
Fastest way to remove image,then follow below steps:
delete all records from
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value'
table because magento is save all product image data at those table.
Then index from Index management from admin for set image black.
Then remove image from dir then goto Your magento dir at media/catalog/product and from this folder delete all file.
Another Process:
Andy Simpson,you need a script which is delete all product from your system which will delete from DB and file system.
Step1: Create a php at root direct of magento system which include Mage.php at first code.
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Step2: set current store is admin and set Developer mode
Mage::app('admin');
Mage::setIsDeveloperMode(true);
Step3: Get Product Collection and create a loop for get one product by one by one
$productCollection=Mage::getResourceModel('catalog/product_collection');
Step4: fetch product image by one and remove image one using below code:
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
FULL CODE:
<?php
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);
$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product){
echo $product->getId();
echo "<br/>";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
echo "<br/>";
$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
echo "<pre>";
print_r($MediaGallery);
echo "</pre>";
foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
$DirImagePath=str_replace("/",DS,$eachImge['file']);
$DirImagePath=$DirImagePath;
// remove file from Dir
$io = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
}
}
If you want to remove more products like 1000 or 5000 then use bottom one with direct query.
Before try this one take backup of your database
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
set_time_limit(0);
ini_set('display_error','1');
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_write');
$id = 101;
$product = Mage::getModel('catalog/product')->load($id);
$q = "DELETE FROM `catalog_product_entity_media_gallery` where entity_id = '".$product->getId()."'";
$connection->query($q);
?>
Accessing the Database for such things is a bad idea.
You can delete images ( or reorder them by changing the 'position' value ) using the following snippet in a custom module ( for the sake of simplicity i'm using ObjectManager, but you should place ProductFactory and ProductRepositoryInterface in the constructor )
$objectManager = ObjectManager::getInstance();
//Get ProductFactory in order to instatiate the Product Object
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
//We have to use ProductRepositoryInterface in order to save the changes bellow to the product
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
//Load a Product by ID in this case 1
$product = $productFactory->create()->load(1);
//Gets an array containing arrays representing each image in the gallery
$mediaGalleryEntries = $product->getMediaGalleryEntries();
//Here we delete every image, you can use conditions in foreach
foreach ($mediaGalleryEntries as $key => $imageEntry) {
unset($mediaGalleryEntries[$key]);
}
//Finally set the altered entries and save using productRepository
$product->setMediaGalleryEntries($mediaGalleryEntries);
$productRepository->save($product);
The code above tested in Magento 2.3 and it also removes images from the filesystem. You can use it to either delete or alter an entry ( change position, image roles etc )
To view each imageEntry you can access its data using $imageEntry->getData()
I had to do something similar not too long ago - needed to replace all product images during an import.
This link helped a lot: http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/
Hopefully it will give you a nudge in the right direction.
DELETE FROM catalog_product_entity_media_gallery WHERE value_id NOT IN (SELECT * FROM (SELECT MIN(value_id) FROM `catalog_product_entity_media_gallery` GROUP BY LEFT(value,17), entity_id having count(*) > 1) x)
why 17 ?
The expamle you have duplicate like this:
/0/0/000116810609_1.jpg
/0/0/000116810609_2.jpg
/0/0/000116810609_3.jpg
/0/0/000116810609_4.jpg
LEFT(value,17)
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
No they are duplicates ;)
Place the below script in magento root and execute
<?php
require_once("app/Mage.php");
umask(0);
Mage::app();
$ob = new Clean();
$ob->removemedia();
Class Clean {
function removemedia() {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $read->select()
->from('catalog_product_entity_media_gallery', '*')
->group(array('value_id'));
$flushImages = $read->fetchAll($select);
echo count($flushImages);
$array = array();
foreach ($flushImages as $item1) {
$array[] = $item1['value'];
}
$valores = $array;
$pepe = 'media' . DS . 'catalog' . DS . 'product';
$leer = $this->listDirectories($pepe);
foreach ($leer as $item) {
try {
$item = strtr($item, '\\', '/');
if (!in_array($item, $valores)) {
$valdir[]['filename'] = $item;
unlink('media/catalog/product' . $item);
}
} catch (Zend_Db_Exception $e) {
} catch (Exception $e) {
//Mage::log($e->getMessage());
}
}
}
function listDirectories($path) {
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (($entry = readdir($dir)) !== false) {
if (preg_match('/^\./', $entry) != 1) {
if (is_dir($path . DS . $entry) && !in_array($entry, array('cache', 'watermark'))) {
$this->listDirectories($path . DS . $entry);
} elseif (!in_array($entry, array('cache', 'watermark')) && (strpos($entry, '.') != 0)) {
$this->result[] = substr($path . DS . $entry, 21);
}
}
}
closedir($dir);
}
}
return $this->result;
}
}

Magento - Move a category programmatically

How do I move a category to another category with all child categories?
I have tried the following solution:
$nodeId = 2269;
$parentId = 2268;
$tree = Mage::getResourceModel('catalog/category_tree')->load();
$node = $tree->getNodeById($nodeId);
$parentNode = $tree->getNodeById($parentId);
$parentChildren = explode(',', $parentNode->getChildren());
$afterId = array_pop($parentChildren);
$prevNode = $tree->getNodeById($afterId);
if (!$prevNode || !$prevNode->getId()) {
$prevNode = null;
}
$tree->move($node, $parentNode, $prevNode);
However my result is somewhat twisted. If I move to the root-category the move works, but if I move to a child-category I get faulty results and disappearing categories.
These are the values of the field path in the database:
Old: 1/2/3/2175/2269
New: 1/2/3/2175/2226/2268/2269
Correct: 1/2/3/2226/2268/2269
The solution was quite simple, this one doesn't mess up the paths. However it feels like this method is slower.
$categoryId = 2269;
$parentId = 2268;
$category = Mage::getModel('catalog/category')->load($categoryId);
$category->move($parentId, null);
$parent = Mage::getModel('catalog/category')->load('REPLACE_WITH_PARENT_ID');
$category = Mage::getModel('catalog/category');
$category->addData(array('name' => 'YOUR_CATEGORY_NAME', 'path' => $parent->getPath()));
$category->save();

Resources