Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set image to category programmatically in Magento

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.

like image 471
krachid Avatar asked Nov 04 '22 20:11

krachid


2 Answers

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.

like image 108
krachid Avatar answered Nov 09 '22 17:11

krachid


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".

like image 22
Tymoteusz Motylewski Avatar answered Nov 09 '22 15:11

Tymoteusz Motylewski