2

I'd like to remove products from a category after a set time (day/week).

My idea was to create a cron file, starting with this to get all products in that category:

$category_id = 6235;
$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getResourceModel('catalog/product_collection')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->addCategoryFilter($category);

Then remove all products from that category:

foreach($products as $product){
    Mage::getSingleton('catalog/category_api')->removeProduct($category->getId(),$product->getId());
}

Is this the right direction? I'm getting a cron error that the catalog_category_flat table doesn't exist. Looking into the db, only catalog_category_flat_1, _2 etc exist (e.g. per store). How do I resolve this error?

Full script:

<?php
require_once 'app/Mage.php';
Mage::app();

$category_id = 6235;
$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getResourceModel('catalog/product_collection')
    ->setStoreId(2)
    ->addCategoryFilter($category);

foreach($products as $product){
    Mage::getSingleton('catalog/category_api')->removeProduct($category->getId(),$product->getId());
}
?>
1

Cronjobs run from the command line and unless you explicitly set a store id it will run as 0. This means ->setStoreId(Mage::app()->getStore()->getId()) won't work. You'll have to use a fixed ID like ->setStoreId(1)

| improve this answer | |
  • So I changed Mage::app()->getStore()->getId() to just 2 (a store that exists) but it's still giving me the same error. Is the problem then on the line $category = ... or Mage::getSingleton... or both? – Michael May 19 '15 at 20:01
  • Could you post the whole script in your question for more context? – Sander Mangel May 19 '15 at 20:07
  • Ok i've added the full script – Michael May 19 '15 at 20:35
0

You can not use single to object and Use model object

Mage::getModel('catalog/category_api')

remove

Mage::getSingleton('catalog/category_api')

Also as sander say you need to specify Store id

| improve this answer | |
  • I'm now using Mage::getModel('catalog/category_api')->setStoreId(2)->removeProduct... but it's giving me this error: Call to undefined method Mage_Catalog_Model_Category_Api::setStoreId() – Michael May 20 '15 at 7:46
  • you cannot use setStoreId() on this Mage::getModel('catalog/category_api') – Amit Bera May 20 '15 at 7:56
  • Understood, but after removing it, I'm back at the original error: catalog_category_flat' doesn't exist'. I have set the store id on the $category and $products lines – Michael May 20 '15 at 9:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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