So I have a question, I'm doing a Cron Job for magento where evaluates the date that the administrator puts in one attribute and the category where the product it's going in another attribute(drop-down list), and when the Cron Jobs execute it has to put that product in that specific category that was set on the attribute.

So far I have

   //gets actual date
   $date = Mage::getModel('core/date')->date('Y-m-d H:i:s');
   $collection = Mage::getModel('catalog/product')->getCollection();    
   $collection->addfieldtofilter('news_from_date', array(array('to' => $date)));
   foreach($collection as $product) {
      //here it should put the product in the specific category

I hope you guys can help me!

Thanks in advance!


Try the following:

   $targetCategoryId = "12";
   foreach($collection as $product) {
       $currentCategories = explode(',',$product->getCategoryIds());
       $currentCategories[] = $targetCategoryId; // add to the array
       $product->setCategoryIds(join(',',$currentCategories)); // join with commas and set to product

| improve this answer | |
  • perfect!! but its work better with array_push($currentCategories, $targetCategoryId); – dzuritaa Jul 23 '13 at 22:44
  • 1
    I'm always willing to learn... tell me how that works better? – philwinkle Jul 23 '13 at 22:49
  • 2
    It's better only if you need to append multiple values to the array. Where a single item is being added it is better to use $array[] = because there is no overhead of calling a function. For reference: php.net/manual/en/function.array-push.php – davidalger Jul 24 '13 at 0:31

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.