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/
Related
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>";
}
}
?>
I'm making a ecommerce website with a CMS where I can edit, add products etc, when I add a product and choose and image from my computer it does not upload to my folder I made for images "uploads".
Does anyone know the solution to this, it's probably in my code but I can't seem to figure it out.
If I manually add the image to the folder uploads and choose the image when I add the product the image shows.
Here is my code:
function add_product() {
if(isset($_POST['publish'])) {
$product_title = escape_string($_POST['product_title']);
$product_category_id = escape_string($_POST['product_category_id']);
$product_price = escape_string($_POST['product_price']);
$product_description = escape_string($_POST['product_description']);
$short_desc = escape_string($_POST['short_desc']);
$product_quantity = escape_string($_POST['product_quantity']);
$product_image = escape_string($_FILES['file']['name']);
$image_temp_location = escape_string($_FILES['file']['tmp_name']);
move_uploaded_file($image_temp_location, UPLOAD_DIRECTORY . DS . $product_image);
$query = query("INSERT INTO products(product_title, product_category_id, product_price, product_description, short_desc, product_quantity, product_image) VALUES('{$product_title}', '{$product_category_id}', '{$product_price}', '{$product_description}', '{$short_desc}', '{$product_quantity}', '{$product_image}')");
$last_id = last_id();
confirm($query);
set_message("New Product with id {$last_id} was Added");
redirect("index.php?products");
}
}
The UPLOAD_DIRECTORY is a path that I have configured in a file named config.php and it looks like this:
defined("UPLOAD_DIRECTORY") ? null : define("UPLOAD_DIRECTORY", __DIR__ . DS . "uploads");
I'm adding an upgrade for the WordPress plugin which I have developed ages ago. This plugin is just a product catalog, so just show products and their images. Products can have more than one images.
I was re-sizing images in the older version of the plugin by CSS, assigning them width and height. Which was working but images look stretched but users were happy. Now I have added a new feature in the plugin which is to crop and re-size from the uploaded image and save it with a different name, like a thumbnail.jpg.
The new feature is working remarkably for the new users who upload images, but the thing is about old users who upgraded to newer version.
The issue is old users already has products and images. When I try to get all the products and images via foreach loop, it works perfectly on 200 - 250 images but breaks on more than 250+ images - No Error :(
Many of my old users has 600+ images so I want a way to crop and re-size the existing images and saves them with a new name and save the file names in the DB.
I'm using wordpress's default wp_get_image_editor(); function.
Here's my query to get old products which has images:
$wpc_product_images_sql = "Select wpc_posts.*, wpc_meta.* From " . $wpdb->posts . " As wpc_posts Inner Join " . $wpdb->postmeta . " As wpc_meta On wpc_posts.ID = wpc_meta.post_id Where wpc_meta.meta_key = 'product_images' Order By wpc_posts.post_title;
And here's my foreach loops (I'm using two loops. First one is getting the products which has images and the second loop is for get images from each post, as I'm mentioned earlier in my question that products can have more than one images. So have to use two loops)
foreach ($wpc_images_qry as $wpc_prod_images) {
echo '<div class="wpc_image_body">'
. '<h3>' . $wpc_prod_images->post_title . '</h3>'
. '<div class="wpc_images">';
$wpc_post_id = $wpc_prod_images->ID;
$wpc_product_images = get_post_meta($wpc_post_id, 'product_images', true);
$big_img_name = array();
foreach ($wpc_product_images as $wpc_prod_img) {
/// For Big
$big_resize_img = wp_get_image_editor($wpc_prod_img['product_img']);
if (!is_wp_error($big_resize_img)) {
$product_big_img = $wpc_prod_img['product_img'];
$product_img_explode = explode('/', $product_big_img);
$product_img_name = end($product_img_explode);
$product_img_name_explode = explode('.', $product_img_name);
$product_img_name = $product_img_name_explode[0];
$product_img_ext = $product_img_name_explode[1];
$big_crop = array('center', 'center');
$big_resize_img->resize($wpc_image_width, $wpc_image_height, $big_crop);
$big_filename = $big_resize_img->generate_filename('big-' . $wpc_image_width . 'x' . $wpc_image_height, $upload_dir['path'], NULL);
$big_resize_img->save($big_filename);
$big_img_name[]['wpc_big_img'] = $upload_dir['url'] . '/' . $product_img_name . '-big-' . $wpc_image_width . 'x' . $wpc_image_height . '.' . $product_img_ext;
if (file_exists($upload_dir['path'] . '/' . $product_img_name . '-big-' . $wpc_image_width . 'x' . $wpc_image_height . '.' . $product_img_ext)) {
echo $upload_dir['path'] . '/' . $product_img_name . '-big-' . $wpc_image_width . 'x' . $wpc_image_height . '.' . $product_img_ext . ' - <strong style="color: #7ad03a;">OK</strong><br>';
} else {
echo $upload_dir['path'] . '/' . $product_img_name . '-big-' . $wpc_image_width . 'x' . $wpc_image_height . '.' . $product_img_ext . ' <strong style="color: red">:(</strong><br>';
}
}
}
update_post_meta($wpc_post_id, 'wpc_big_images', $big_img_name);
echo '</div>'
. '</div>';
}
You might try adding the new image size with
add_image_size()
and then run
https://wordpress.org/plugins/regenerate-thumbnails/
which surely has a solution to the timeout problem.
There is a way to display a message for your plugin users upon update, ask them to install and run the plugin if they have old images.
Hope that works for you.
If you want resize image mean follow these one, it resize your image whenever upload image in media,
add_filter('wp_handle_upload_prefilter','aj_handle_upload');
function aj_handle_upload($file)
{
add_image_size( 'mobile', 360, 0, array( 'center', 'center' ));//mobile is userdefined name.
add_image_size( 'desktop', 700, 0, array( 'center', 'center' ));//desktop & tablet is user defined name.
return $file;
}
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.
I'm making a page with some flash games, but, since in the past will be many games it will be very bored to add all those games one by one on the site. I know that using PHP we can get the list of the files in the directory and I know that, using this method, I can display all the games on the directory to the visitors page but, I was thinking if you can help me to add an image to each game that corespond with the name of the game. Ex:
In "games" folder we will have games: play1.swf, play2.swf, play3.swf
and, in "images" directory we will have images: play1.jpg, play2.jpg, play3.jpg.
To display the list of the games, can we make a combination of jpg files with swf files? Play1.jpg will be the image of play1.swf game and, when a visitor clicks on the image, will be redirect to a page named ex: playgames.php?play1
assuming this directory structure:
/foo/images
game1.jpg
game2.jpg
/foo/games
game1.swf
game2.swf
Something like this:
<?php
$dir = "/foo";
$files = new DirectoryIterator($dir . DIRECTORY_SEPARATOR . 'games');
$games = array();
foreach($files as $file){
if (!$file->isDot()) {
$potential_image_location = $file->getPath() . '/../images/' . $file->getBasename('.swf') . '.jpg';
if (file_exists($potential_image_location)) {
$games[$file->getBaseName()] = array(
'game_path' => $file->getPathname(),
'image_path' => realpath($potential_image_location),
);
}
}
}
if (!count($games)) {
die("Sorry, couldn't find any game / image combos");
}
?>
<table>
<?php
foreach ($games as $game_name => $info) {
echo '<tr><td><img src="' . htmlentities($info['image_path']) . '" alt="' . htmlentities($game_name) . '"></td>' . PHP_EOL;
echo '<td>' . $info['game_path'] . '</td></tr>';
}
?>
</table>
its all about using opendir in a clever way, heres the docs on it http://php.net/manual/en/function.opendir.php