Updating Meta Title in Magento via PHP script causes unwanted events - magento

On our Magento 1.5.0.1 I wrote a PHP script to update all of our product meta titles to be based on the name and SKU of each product. The script is run by calling PHP via SSH.
After running the script I noticed in our M2E Pro (the eBay syncing module) that every single product appears to have become disabled.
Looking at the actual products they aren't disabled, so it appears my script is somehow faking the event.
Out of our 3,000+ products, though, one of them was disabled and subsequently M2E Pro removed the listing from eBay.
Here is my script:
<?php
set_time_limit(0);
define('MAGENTO', "/home/discount/public_html");
require_once MAGENTO . '/app/Mage.php';
error_reporting(E_ALL);
ini_set('display_errors', '1');
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$storeId = Mage::app()->getStore('default')->getId();
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToSelect('meta_title');
$total = count($products);
$count = 1;
foreach ($products as $product)
{
$mt = sprintf("%s [%s]", $product->getName(), $product->getSku());
$sku = $product->getSku();
if ($product->getMetaTitle() != $mt)
{
$percent = $count / $total;
echo $sku." ".$percent."\n";
$product->setMetaTitle($mt);
$product->save();
}
}
?>
I'd like to know what I need to do to my script to make it correctly update the meta title without causing odd events?

Stab in the dark here, but it's a good chance the M2E extension has an event listener setup for model/product saves, and in that event listener does things depending on product state.
By itself this isn't a problem, but when you load an EAV model via its collection it loads the bare minimum of attributes. Since you haven't explicitly loaded product status via addAttributeToSelect this may be confusing the M2E extension. Trying adding the status attribute. If that doesn't work try addAttributeToSelect('*') — M2E may be checking other attributes as well to decide when to pull things.
Finally, when you load an EAV model via a collection their afterLoad isn't called. It's possible the M2E extension (naively) assumes something that happens in afterLoad will have happened, so you may want to call it explicitly for each product.
$product->afterLoad();
Short of that, you'll need to reverse engineer M2E to the point in the code where it's doing it's above logging and determine why it thinks it needs to disable a product. Since this is a commercial extension, I'd reach out to the developers. If you pay for something you deserve some level of support.

<?php
//increase the max execution time
#ini_set('max_execution_time', -1);
//memory_limit
#ini_set('memory_limit', -1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Start Despaly All Product Meta Title And Description
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$categories = Mage::getModel('catalog/category')
->getCollection()
// magic is prepared here..
->addAttributeToSelect('*')
// then the magic happens here:
->addAttributeToFilter('level', array('eq'=>4))
->load();
if (count($categories) > 0):
foreach($categories as $category):
$catId = $category->getId();
$category = Mage::getModel('catalog/category')->load($catId);
$resource = Mage::getResourceModel('catalog/category');
//if($catId==1465): //If Update Specific category Value by Id
$CategoryName = $category->getName();
$metaTitle = "Buy ".$CategoryName." Test Title";
$metaDescription = "Shop your favourite ".$CategoryName." Test Description";
$category->setData('meta_title', $metaTitle);
$resource->saveAttribute($category, 'meta_title');
$category->setData('meta_description', $metaDescription);
$resource->saveAttribute($category, 'meta_description');
$check = $category->getMetaTitle();
echo "<pre>";
print_r($catId);
echo "<pre>";
print_r($check);
echo "\n";
//endif;
endforeach;
else: echo "No Results";
endif;
?>

Related

For loop is working only once

For the below code, where I am trying to update a custom attribute called branding. The for loop is running only for one iteration and stopping. It is updating only the first product in the list and not looping any further.
Can anyone kindly let me know why this is happening?
<?php
set_time_limit(0);
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $product){
echo $product->getSku();
$product->setData('branding', 'kib');
$product->save();
}
Instead of saving total product just save attribute for product by using saveAttribute
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
echo $products->getSelect();//this will give sql query just run your db.
foreach($products as $product)
{
$product->setBranding('kib');
$product->getResource()->saveAttribute($product, 'branding');
}
One more solution without loops
$store_id = 0;
$product_ids = Mage::getModel('catalog/product')
->getCollection()
->getAllIds();//you can apply some filters also
Mage::getSingleton('catalog/product_action')->updateAttributes(
$product_ids,//array of ids
array('branding' => 'kib'),//you can add some other attributes also as key value pair
$store_id
);

add product to wishlist in magento API

I have checked in magento soap API but I can not find API for add product to wish list so I am developing own API but I don't know what is the problem with my code so please help me to find solution.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app();
$customer_id = $_GET['customer_id'];
$product_id = $_GET['product_id'];
$customer = Mage::getModel('customer/customer');
$wishlist = Mage::getModel('wishlist/wishlist');
$product = Mage::getModel('catalog/product');
$customer->load($customer_id);
$wishlist->loadByCustomer($customer_id);
$res = $wishlist->addNewItem($product->load($product_id));
if($res)
{
$status =1;
$message = "your product has been added in wishlist";
}
else
{
$status =0;
$message = "wrong data send";
}
$result = array("status" =>$status,"message"=>$message);
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
?>
There is a similar question you might want to check.
In your code you are not extending Magento API in any way but creating a standalone hackish script that inserts items to wishlist. I suggest that you take a look on how to develop a magento extension or if you need to create a backend (CLI) script, at least use the same structure as in shell/abstract.php and extend the shell base class - you will save yourself loads of headaches.
Moreover, your code is not secure, maintainable and removes all the benefits of using Magento as an ecommerce platform/framework (security, authorization & authentication etc)
Inchoo have quite some blog posts that could give you an idea where to begin
http://inchoo.net/magento/magento-api-v2/
http://inchoo.net/magento/extending-the-magento-api/
/* error_reporting(E_ALL);
ini_set("display_errors", 1);*/
You Have Comment This line And Write this
require_once './app/Mage.php';

Magento 1.9 - resave all products

I need to re-save all products in magento. I found solution (for 1.7 version):
<?php
set_time_limit(0);
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $product) {
echo $product->getName() . '<br/>';
// save the product
$product->save();
}
echo 'DONE';
?>
But this not working for magento 1.9.
I need to re-save all configurable products, if it possible.
It works, but you cannot see product name, try use sku field

Magento - How to get attributes of a child product of a bundled item

I need to retrieve a simple text attribute from a child product belonging to a bundled product if it exists. This needs to be done on the shopping cart page. The below is the code I've been messing around with to see what I can retrieve.
The file is template/checkout/cart/item/default.phtml in the theme folder.
$_item = $this->getItem();
$_product = $this->getProduct();
$_product = Mage::getModel('catalog/product')->load($_product->getId());
$isVisibleProduct = $_item->getProduct()->isVisibleInSiteVisibility();
$itemsCollection = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach($itemsCollection as $item) {
echo $item->getId();
$_bProduct = Mage::getModel('catalog/product')->load($item->getId());
echo '<pre>';
var_dump($_bProduct);
echo '</pre>';
echo '<br>';
echo $_bProduct->getData('backorder_shipment_date');
}
To access custom attributes on all pages, you should use :
getItemCollection()
or
getProductCollection()
also, check this link Accessing Custom Product Attributes in the Cart/Checkout Area

Magento: Filter products by Status

I'm having some serious Magento issues here. As expected the following:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 1));
Will return all enabled products for my $category_id. However this:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 0));
Does not return disabled products. I can't seem to find a way to return disabled products, and I don't know why.
I've tried this:
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Which was meant to have worked, but apparently may have been deprecated.
Does anyone know how to get all products in a category, enabled and disabled?
Don't worry, you simply got trapped by a very unusual constant definition^^. Just try:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter(
'status',
array('eq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED)
);
For whatever reasons Varien decided to define this STATUS_DISABLED constant with a value of 2, instead of the more intuitive (and commonly used) value of 0.
I think you can do this by setting store to default like
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
make sure you save the current store value and set it back after doing the above.
Or by using a script from outside magento and invoke mage by
require_once '../app/Mage.php';
$app = Mage::app();
Mage::register('isSecureArea', true);
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->setOrder('price', 'ASC');
I haven't found an answer as such to my question above. But I have saved a lot of time by using a different method.
I exported a CSV of all the products in my Magento, deleted all columns except Category ID and SKU (this is all I needed), and then filtered that to return all the skus instead.
If it helps anyone here is the code -
<?php
$file = fopen('allprods.csv', 'r');
// You can use an array to store your search ids, makes things more flexible.
// Supports any number of search ids.
$id = array($_GET['id']);
// Make the search ids safe to use in regex (escapes special characters)
$id = array_map('preg_quote', $id);
// The argument becomes '/id/i', which means 'id, case-insensitive'
$regex = '/'.implode('|', $id).'/i';
$skus = array();
while (($line = fgetcsv($file)) !== FALSE) {
list($ids, $sku) = $line;
if(preg_match($regex, $ids)) {
$skus[] = $sku;
}
}
$count = count($skus);
$i = 1;
echo $category_id;
foreach ($skus as $sku){
echo $sku;
if($i != $count) { echo "`"; }
$i++;
}
This solution was created by using a previous topic about filtering CSVs, here
So for now, I can survive. however - an answer to this question is still needed!
Nothing works if catalog_flat_product is on in backend configuration->catalog.
try this..this will give all the products enabled and disabled ultimately
$collection = Mage::getResourceModel('catalog/product_collection'); //this will give you all products
foreach($collection as $col)
{
$var = Mage::getModel('catalog/product')->loadByAttribute('sku',$col->getSku());
echo"<pre>";print_r($var->getData());echo"</pre>";
}
its really simple and after this you can easily filter products by status

Resources