Magento: Filter products by Status - magento

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

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
);

Updating Meta Title in Magento via PHP script causes unwanted events

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;
?>

Magento - Get product name for all languages

When reading all magento products for a export extension I've encountered a problem:
when trying to get the name of a product by using getName() on the loaded model you only get the active language name or if that is not set the default name of the product. But I need to get all product names for default, english, german, french, etc.
Does anyone have a solution for this problem or an idea how to solve it?
$model = Mage::getModel('catalog/product');
$collection = $model->getCollection();
foreach ($collection as $product) {
$id = $product->getId();
$model->load($id);
$name = $model->getName(); // gives you only the active language name / default name
}
Since you also want the default store, I'm only aware of one working way:
$aStoreHash = Mage::getModel('core/store')
->getCollection()
->setLoadDefault(true)
->toOptionHash();
$aName = array();
foreach ($aStoreHash as $iStoreId => $sStoreName) {
Mage::app()->setCurrentStore($iStoreId);
$oCollection = Mage::getModel('catalog/product')
->getCollection()
// Uncomment next line for testing if you have thousands of products
// ->addFieldToFilter('entity_id', array('from' => 1, 'to' => 5))
->addAttributeToSelect('name');
foreach ($oCollection as $oProduct) {
$aName[$oProduct->getId()][$iStoreId] = $oProduct->getName();
}
}
var_dump($aName);
If you don't need the default store, you could drop Mage::app()->setCurrentStore($iStoreId); and use ->addStoreFilter($iStoreId) on the collection instead.

How do I get the options for bundled products on the success page?

On the success page, I have no trouble getting a list of the products purchased with the following code:
$order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
foreach ($order->getAllItems() as $item){
$subtotal = number_format($item->getSubtotal(),2);
}
What I can't figure out, is how to get an object or an array of the options for bundled products. These are standard options like what color a product is.
I have not specifically tried this with bundled products, but the code below works with configurable products, and I'm sure you can modify it as needed to fit your situation.
$order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
foreach ($order->getAllItems() as $item){
$productOptions = $item->getProductOptions();
if (isset($productOptions['attributes_info'])) {
foreach ($productOptions['attributes_info'] as $productOption) {
echo $label = $productOption['label'];
echo '<br />';
echo $value = $productOption['value'];
}
}
}
My suggestion is to start broad (i.e. at the $item level), see what Magento returns (using Zend_Debug::dump($item->getData()), and then work your way down to what you need.
Hope that helps.

$item->getProduct()->getQty not working in magento

I wrote a function in shipping.php. I want to get the quantity from each product in the cart. I am using $item->getProduct()->getQty, but this is not working.
Is there any other method?
Have you tried $item->getQty() ?
For future readers: look into the relevant source code, e.g app/code/core/Mage/Sales/Model/Order/ to find the exact API.
In that case, the code you are looking for is probably $item->getQtyOrdered(). Not sure which one you're referring to above.
$cart = Mage::getModel('checkout/cart')->getQuote();
$result = array();
$i = 0;
foreach ($cart->getAllItems() as $item) {
$result[$i]['id'] = $item->getProduct()->getId();
$result[$i]['name'] = $item->getName();
$result[$i]['sku'] = $item->getSku();
$result[$i]['price'] = $item->getPrice();
$result[$i]['qty'] = $item->getQty();
$i++;
}
echo "<pre>";
print_r($result);
Try this.
You can use
$item->getId();
to get the cart product ID too.
$item->getProduct()->getQty; will be returned by NULL;

Resources