1

I have this script to hide empty categories:

require_once '../app/Mage.php';
Mage::app()->setCurrentStore(0);

$categories = Mage::getModel('catalog/category')->getCollection()
                                                ->addAttributeToSelect('*')
                                                ->addAttributeToFilter('level',array('gt'=>2));

foreach($categories as $category)
{
    $products = $category->getProductCollection()
                          ->addAttributeToFilter('status', 1);
    if(!$products->count()) {
        echo $category->getName().'-';
        $category->setIsActive(0);
    } else {
        $category->setIsActive(1);
    }
    $category->save();
}

It hides categories with only de-activated products. But how can i extend this with a filter on products which have stock management, but are out of stock?

1 Answer 1

0

The Status that you are looking at is wether or not the product is Enabled, not wether or not it is in stock. Since you want to know if its managed or not and currently in stock you will want to join the product against the stock information.

$collection = Mage::getModel('catalog/product')->getCollection();

// Join The inventory stock and product collections together
$collection->joinTable(
    array('inv' => 'cataloginventory/stock_item'),
    'product_id = entity_id',
    array("stock_status" => "is_in_stock","manage_stock")
)->addAttributeToSelect('stock_status');

foreach($collection as $_item) {
    if($_item->getManageStock()) {
        // Stock is Managed 
    }
    if ($_item->getStockStatus()) {
        // Is in Stock 
    }

    if ($_item->getManageStock() && $_item->getStockStatus()) {
        // Is a managed stock item that is currently in stock. 
    }
}
2
  • Thanks, but how do I combine these? If a categorie has no active products and no "Stock managed" products in stock, the categorie has to be disabled.
    – Martijn
    May 24, 2015 at 14:59
  • Hello, if the count on the collection of products is 0 then there is no products, so a straight forward if statement can handle that check. May 24, 2015 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.