magento addImageToMediaGallery is not working - php

i was trying to add images into magento products programmatically but no luck.
i find the function addImageToMediaGallery can do that but its not working
$p = Mage::getModel('catalog/product')->load($id);
// save product
foreach ($imgs as $k => $img) {
$img_path = Mage::getBaseDir('media'). $img;
if( !$k ) {
$p->addImageToMediaGallery( $img_path , array('small_image', 'thumbnail', 'image'), false, false);
} else {
$p->addImageToMediaGallery( $img_path , array(), false, false);
}
$p->save();
}
what i know
product is loading successfully i try $p->getName() and i get the title
the paths are correct, images do live in /home/tronixco/public_html/caskyco/media/temp_images/dji_phantom_4_drone_4k_hd_camerea_3_axis_gimbal_5km_range_with_28_minutes_flight_time_manfrotto_bag_pack_4_.jpg
addImageToMediaGallery is doing some work as it copy the images to catalog/product/d/j...
in the admin panel product_edit there is nothing , like no image have been uploaded what so ever
im running an external script and not getting any logs in var folder neither any error in error_logs files
this whole code is running inside a function product_add_images( $id , $images )
magneto version is 1.9.2.4

<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$importDir = Mage::getBaseDir('media') . DS . 'bulkimages/101/';
$productsData = array('Purple-Crown-Ring-MFAS.jpg','Purple-Crown-Ring-MFC.jpg','Purple-Crown-Ring-MSAS.jpg','Purple-Crown-Ring-MSF.jpg');
$productSKU = '111';
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
foreach($productsData as $fileName){
$filePath = $importDir.$fileName;
if (file_exists($filePath)) {
$ourProduct->addImageToMediaGallery($filePath, array('image', 'small_image', 'thumbnail'), false, false);
$ourProduct->save();
echo "done ";
} else {
echo $productSKU . " not done";
echo "<br>";
}
}
?>

Related

How to update image_path in laravel

i'm want to delete existing images and update with new images using in laravel using this method
if($request->hasFile('images')) {
$listingImages = $listing->images;
foreach($listingImages as $listingImage) {
$img_path = 'images/listing/'.$listing->id;
if(File::exists($img_path)) {
File::deleteDirectory($img_path);
$listingImage->delete();
}
foreach ($request->file('images') as $image) {
$listingImage = new ListingImage;
$imageName = time().'.'.$image->getClientOriginalExtension();
$listingImage->listing_id = $listing->id;
$listingImage->image_path = 'images/listing/'.$listing->id."/".$imageName;
$listingImage->save();
$image->move(public_path('images/listing/'.$listing->id),$imageName);
}
}
}
so far i can delete the previous directory and update new image path on the database.
but each time i run the edit listing, I get a Symfony\Component\HttpFoundation\File\Exception\FileException
The file "8 (2).jpg" was not uploaded due to an unknown error. and the old listingImages isn't been deleted on my database.
what proper way can i use to achieve updating multiple listing images?
try Storage::delete() function ref link https://laravel.com/docs/7.x/filesystem#deleting-files
and don't delete Directory i think in future u can need to image in that Directory
if ($request->hasFile('images')) {
$listingImages = $listing->images;
foreach ($listingImages as $listingImage) {
foreach ($request->file('images') as $image) {
$oldImage = $listingImage->image_path;
$listingImage = new ListingImage;
$imageName = time() . '.' . $image->getClientOriginalExtension();
$listingImage->listing_id = $listing->id;
$listingImage->image_path = 'images/listing/' . $listing->id . "/" . $imageName;
$listingImage->save();
$image->move(public_path('images/listing/' . $listing->id), $imageName);
\Storage::delete($oldImage); // it will not work if u r not setup `Storage`
//then u can use unlink
unlink(public_path().'/'.$oldImage); //
}
}
}

import images into magento

I have several products and want to give them all the same image with the path:
/media/import/pic.jpg
This is just for a test. Later, I will add different images to each product so some parts of the code seem unnecessary.
That's what i came up with:
<?php
require_once('app/Mage.php');
umask(0);
Mage::app();
$importDir = Mage::getBaseDir('media') . DS . 'import/';
$fileName = "pic.jpg";
$_productCollection = Mage::getModel('catalog/product')
->getCollection()->addAttributeToSelect('*');
foreach($_productCollection as $_product)
{
$filePath = $importDir.$fileName;
if ( file_exists($filePath) ) {
try {
$_product->addImageToMediaGallery($filePath, 'image', false);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
It does not work at all. What's wrong with it?
Try setting the store id to admin
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Uploading multiple image with different input file in Codeigniter

So I have four input files in my forms and I send it on my global $_FILES with the following indices: front,rear,right and left.
I want to upload these using codeigniter image class library. This is my code:
public function upload_to_temp($id, $folder, $tags){
$path = realpath(APPPATH . '../public/resources/temps/' . $folder );
//makes a directory
mkdir($path . '/' . $id, 0700);
//navigate to the newly created path
$path = realpath(APPPATH . '../public/resources/temps/' . $folder . '/' . $id);
if(isset($tags)){
//use these tags to check the files present on submission
foreach($tags as $tag){
if(array_key_exists($tag,$_FILES)){
if(!empty($_FILES) && $_FILES[$tag]["name"] != "" && isset($_FILES[$tag]["name"])){
$config = array (
'source_image' => $_FILES[$tag]["name"],
'image_library' => 'gd',
'upload_path' => $path,
'file_name' => $id . '_' . $tag . '.jpg',
'allowed_types' => 'png|jpg|jpeg',
'overwrite' => TRUE,
'max_size' => '2000',
);
$this->_CI->upload->initialize($config);
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image. ';
echo $this->_CI->upload->display_errors();
}else{
echo 'Success saving to temp folder';
}
//kapag failed
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image.';
echo $this->_CI->upload->display_errors();
}else{
//now, the $path will become our resource path for copying and creating thumbnails.
$resouce_path = $config['upload_path'] . '/' . $config['file_name'];
$this->img_create_thumb($resouce_path, $folder);
}
}else{
//Hindi na dapat marating to!
echo $tag . ' not present ';
}
}else{
//use default pictures
echo $tag . ' not present ';
}
}
}
}
However it gives me the following error:
Error creating image. You did not select a file to upload.Error
creating image.You did not select a file to upload.You did
not select a file to upload.Error creating image. You did not
select a file to upload.Error creating image.You did not select
a file to upload.You did not select a file to upload.right
not present left not present
I think I did not correctly specified which resource on the $_FILES should be uploaded.
Your response would be greatly appreciated.
Thanks
I solved it by supplying the indices in codeigniter's do_upload()
$this->_CI->upload->do_upload($tag);

How To Add Additional Images To A Product In Magento

I can add an image to a product during creating using the following script. However, I'm having trouble loading a product and add additional image to the product media gallery. Do I have to delete the product media gallery and readd all the images at once? It's one image per row in a csv file.
public function addImage($product, $image)
{
$imagePath = $this->downloadImage($image);
$product->setMediaGallery(array('images' => array(), 'values' => array()));
if (is_file($imagePath)) {
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
}
}
Why are you using a script to add images? Adding images in magento can be easily done via the admin interface.
Just login to the admin panel, Catalog > Manage Products > Edit Product > Images (on left panel).
You add the additional images using the following script.
$importDir = Mage::getBaseDir('media') . DS;
// additional images
if ($import_product[29] != '') {
$addImages = explode(",", trim($import_product[29]));
foreach ($addImages as $additional_image) {
$image_directory = $dir .DS.'data'.DS. trim($additional_image);
if (file_exists($image_directory)) {
$product->addImageToMediaGallery($image_directory, null, false, false);
} else {
$image_directory = $dir . 'data' . DS . 'comingsoon.jpg';
$product->addImageToMediaGallery($image_directory, null, false, false);
}
}
echo 'Additional images for product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
}
The $import_product[29] is an array of images separated by commas. Please refer my tutorial as well which explains how to set default image as well.
http://www.pearlbells.co.uk/how-to-add-main-image-and-additional-image-to-the-products-pro-grammatically-magento/

How to delete remain data in WP database after deleting custom post via admin interface

I'm trying to create a plugin that will delete pictures and additional info from database on deleting custom post (sp_venue) via admin panel (wp-admin/edit-tags.php)
In the plugin I'm using this to catch the event:
add_action( 'delete_post', 'kg_delete_post' );
function kg_delete_post($postId) {
$post = get_post($postId);
if ($post->post_type != 'attachment') {
return false;
}
$url = str_replace($dirs['baseurl'],'',$post->guid);
$urlParts = explode("/",$url);
$numberOfParts = sizeof($urlParts) - 1;
$dirs = wp_upload_dir();
$fileNameParts = explode(".", $urlParts[$numberOfParts]);
$fileName = str_replace('.' . end($fileNameParts), '', $urlParts[$numberOfParts]) . "-*." . end($fileNameParts);
$path =$dirs['basedir'] ."/". $urlParts[$numberOfParts-2] . "/" . $urlParts[$numberOfParts-1] . "/";
$fullPath = $path . $urlParts[$numberOfParts];
$fullPathSearch = $path . $fileName;
#unlink($fullPath);
foreach (glob($fullPathSearch) as $filename) {
#unlink($path . $filename);
}
}
It works with:
wp_delete_post($Id, true)
But looks like the event on deleting via admin panel is no the same.
What should i use to make it works?
Thank you.
Solved by adding my js on in admin panel to customize the click on delete button.

Categories