How to Archive Nodes Programmatically In Drupal

Using a hook update

Sergio Guardiola Herrador
1 min readJul 4, 2024
Photo by Nana Smirnova on Unsplash

If you need to update the moderation state of a few contents, you can do it manually. But if you need to do it on several environments like the test server, the UAT server etc, you can automate it so it’s applied automatically on every server. To do so, all you need is a hook update like this, where you only need to pass an array $entityIds with the content IDs you want to update and then run the updates:

use \Drupal\Core\Entity\RevisionLogInterface;

/**
* Archive nodes programmatically.
* @param array $sandbox
*/
function hook_update_9011(array &$sandbox) {
$new_state = 'archived';
$entityIds = [20435, 20733, 19523, 20434, 27896];
foreach ($entityIds as $nid) {
$node = \Drupal\node\Entity\Node::load($nid);
if (isset($node)) {
$node->set('moderation_state', $new_state);
if ($node instanceof RevisionLogInterface) {
$node->setRevisionLogMessage('Changed moderation state to Archived');
$node->setRevisionUserId($node->getOwnerID());
}
$node->save();
}
}
}

👉 Find out more about me here: https://sergioguardiola.net 🔥

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet