2

I have a few 1000 existing entries and just introduced a new Category type. And I would need to assign all existing entries, to a certain category.

I've been looking in the MySQL databases what exactly is going on, so I could reproduce it with a query directly in there, but can't seem to pinpoint exactly what I would need to update.

Any ideas?

1

You could build a plugin to grab all the entries and then assign that new category to it that way.

This bit of code is untested but this should do it, since this is a one off thing, you can get away with just doing it in chunks by setting the limit and offset, otherwise I'd recommend creating this as a Task:

// get all the entries
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "news"; // just using news as an example, be sure to set the appropriate section handle
$criteria->limit = null;
// $criteria->offset = null; // you could use the limit and offset field to do this 200 at a time, to avoid it timing out on you
$criteria->status = null;
$entries = $criteria->find();

$categoryIds = array(222); // this would be the new category (its ID) that you want to assign to the entry, be sure to set the correct ID here

for($i=0; $i<count($entries); $i++)
{
    $entry = $entries[$i]; // for easier reference

    // lets get the existing categories that are assigned to this entry and add it to the new category ID you set a few lines above, if there are no existing categories for this, then you can remove this for loop entirely
    for($c=0; $c<count($entry->categoryFieldHandle); $c++)
    {
        $categoryIds[] = $entry->categoryFieldHandle[$c]->id; // be sure to replace categoryFieldHandle with the category field handle for the category field
    }

    // setting the categories to this field, be sure to replace categoryFieldHandle here too
    $entry->getContent()->setAttributes(array(
        'categoryFieldHandle' => $categoryIds,
    ));

    craft()->entries->saveEntry($entry); // save the entry
}
1

I just found myself doing this exact thing. The trick is to use saveRelations to set the category.

In my example, my category id is 18840, my field is market, and my section is events.

I created a throwaway action in my exiting site plugin:

public function actionSetmarket()
{
  $catIds = array(18840);
  $fieldModel = craft()->fields->getFieldByHandle('market');
  $criteria = craft()->elements->getCriteria(ElementType::Entry);
  $criteria->section = 'events';
  $criteria->limit = null;
  foreach ($criteria as $entry) {
    craft()->relations->saveRelations($fieldModel, $entry, $catIds);
  }
}

Which can be run from /actions/site/setmarket

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.