How to update all pages programatically?

I have made a changed to a blueprint for the value stored in a particular field.

Previously the stored value and display value were both the name.

query:
  fetch: page.parent.colours.toStructure
   text: "{{ structureItem.name }}"
   value: "{{ structureItem.name }}"

Other functionality updates now require me to use unique id’s (autoid) for each.

query:
  fetch: page.parent.colours.toStructure
   text: "{{ structureItem.name }}"
   value: "{{ structureItem.autoid }}"

There are hundreds of affected pages, and I need a way to basically update/re-save each page thereby updating the value stored in the text file.

Using Update page content with the API doesn’t update the pages automatically; I’d have to pass the new value each time. I’d assume the same would be true if I just loop through all the pages in php and fire $page->update(). If a normal update and save was done in the CMS, these values would be updated.

Is there a way to “re-save” each page programatically in a loop, thereby replacing the stored field value with the different property, or do I have to write a script which looks up the ‘autoid’ each time and specifically sets the value on update?

Something like this should do the trick (after making a backup of the /content folder first :wink:):

foreach($site->index(true) as $p) {
  $oldValue = $p->colours()->value();
  $newValue = ... // do your conversion magic here
  // maybe also validate if this particular
  // page `$p` is supposed to be updated
  $p->update([
    'colours' => $newValue,
  ]);
}

The true boolean in index() ensures that also drafts are included. You may further filter the pages collection; if for example only pages of template type foo are to be affected, use $site->index(true)->template('foo') instead etc.

PS: Calling $page->update() repeatedly can result in a time-consuming loop. I did this recently on thousands of pages and ran into server timeouts; if that happens you might have to do it in batches using ->offset() and ->limit() accordingly…