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);
Related
I have a problem:
When I'm trying to flush Magento cache programmatically like this:
$types=array('config','layout','block_html','translate','collections','eav','config_api','config_api2');
foreach($types as $type) {
$c = Mage::app()->getCacheInstance()->cleanType($type);
Mage::dispatchEvent('adminhtml_cache_refresh_type', array('type' => $type));
}
[source]
I have already read this article about Magento cache and it's flushing, but I'm still missing something.
The above method should do the same as does the "Flush Magento Cache" button, but it doesn't in my case. When I'm running a script I'm saving a new controller, but it doesn't work after cache flushing programmatically with the way described above (and many others I have already tried).
But as soon as I perform the same from admin panel manually in the middle of the script's job- it starts working correctly.
Any idea? Does it help, if I will put here scripts code?
Thanks in advance!
Your code seems to be clearing only the block caches, for new controllers/classes, you will need to remove the cache folder, you can do it programmatically like this
/**
* Remove cache folders:
*/
public function cleanFiles() {
try {
flush();
//cache
$dir = Mage::getBaseDir('cache');
$items = array_diff(scandir($dir), array('..', '.'));
foreach ($items as $item) {
$path = $dir . DIRECTORY_SEPARATOR . $item;
is_dir($path) ? $this->_rrmdir($path) : unlink($path);
}
} catch (Exception $e) {
die("[ERROR:" . $e->getMessage() . "]" . PHP_EOL);
}
}
/**
* Removes a directory and all elements contained
* #param string $dir directory to remove
*/
private function _rrmdir($dir) {
if (is_dir($dir)) {
$objects = array_diff(scandir($dir), array('..', '.'));
foreach ($objects as $object) {
$path = $dir . DIRECTORY_SEPARATOR . $object;
is_dir($path) ? $this->_rrmdir($path) : unlink($path);
}
reset($objects);
rmdir($dir);
}
}
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>";
}
}
?>
Hello everyone I'm trying to upload an image to parse with PHP. i was able to add the object all the columns works perfectly except the Image Column stays undefined i checked the php.ini (url_fopen:On ;) and the utf-8 charset and many other solutions i thins its a problem of security or Privilege !! Please if you have any useful Ideas share it and Thanks in Advance !!!
Here is my code
<?php
require_once( 'autoload.php' );
// Add the "use" declarations where you'll be using the classes
use Parse\ParseObject;
use Parse\ParseUser;
use Parse\ParseException;
use Parse\ParseFile;
use Parse\ParseCloud;
use Parse\ParseClient;
use Parse\ParseQuery;
try {
$app_id = "xxxxxxxxxxxxxxxxxxxxxx" ;
$rest_key = "xxxxxxxxxxxxxxxxxxxxxx";
$master_key = "xxxxxxxxxxxxxxxxxxxxxx";
ParseClient::initialize( $app_id, $rest_key, $master_key );
ParseClient::setServerURL('https://parseapi.back4app.com', '/');
if(isset($_GET['libelle']) && (isset($_GET['prix']) ) ){
$libelle = $_GET['libelle'];
$prix = $_GET['prix'];
}
if ( isset( $_FILES['image'] ) ) {
$isFileExists = file_exists ($_FILES['image']['tmp_name'] );
$isGoodSize = ($_FILES['image']['size'] < 600000) && ($_FILES['image']['size'] > 0);
if ( $isFileExists && $isGoodSize) {
// save file to Parse
$file = ParseFile::createFromData( file_get_contents( $_FILES['image']['tmp_name'] ), $_FILES['image']['name'] );
$file->save();
//echo 'File URL: ' . $file->getURL() . '';
} else {
echo "Erreur";
}
}
$Prod = ParseObject::create("Produit");
//$Prod = new ParseObject("Produit");
$Prod->set("libelle",$libelle);
$Prod->set("prix",(float)$prix);
if ( isset( $file ) ) {
$Prod->set("image",$file);
}
try {
$Prod->save();
echo 'Object Saved with ID: <strong>' . $Prod->getObjectId() . '</strong>.<br/>';
} catch (ParseException $ex) {
echo 'Failed to create new object, with error message: ' . $ex->getMessage();
}
} catch (ParseException $ex) {
echo $ex->getMessage();
}
?>
I was checking here more about files! Just for help you, the maximum file size is 20MB. You can test with different file sizes.
At releases page on GitHub from Parse PHP SDK, you can check the version 1.2.8 that fixed a error with ParseFiles.
I would like to develop my application for better functionality. I need to remove a category of articles using a PHP script in Joomla. e.g. I have a main category and subcategory. How can I remove selected subcategory and then run rebuild? Instead using Joomla administrator I would like using own script.
I use folowing sample code to create new subcategory:
<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', '../');
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE . 'includes'.DS.'defines.php' );
require_once ( JPATH_BASE . 'includes'.DS.'framework.php' );
require_once ( JPATH_ADMINISTRATOR .DS. 'components'.DS.'com_categories'.DS.'models'.DS.'category.php');
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
$extension = 'com_content';
$title = 'nowa';
$parent_id = 9;
// JTableCategory is autoloaded in J! 3.0, so...
if (version_compare(JVERSION, '3.0', 'lt'))
{
JTable::addIncludePath(JPATH_PLATFORM . 'joomla/database/table');
}
// Initialize a new category
$category = JTable::getInstance('Category');
$category->extension = $extension;
$category->title = $title;
$category->published = 1;
$category->access = 1;
$category->params = '{"category_layout":"","image":""}';
$category->metadata = '{"author":"","robots":""}';
$category->language = '*';
// Set the location in the tree
$category->setLocation($parent_id, 'last-child');
// Check to make sure our data is valid
if (!$category->check())
{
JError::raiseNotice(500, $category->getError());
return false;
}
// Now store the category
if (!$category->store(true))
{
JError::raiseNotice(500, $category->getError());
return false;
}
// Build the path for our category
$category->rebuildPath($category->id);
When I run this code, I receive new subcategory with assets table.
In the same way I would like remove any category.
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.