Update Content Pathauto Aliases Programatically

Pathauto provides hooks for modifying aliases, but if you want to write an update hook to modify a set of custom entity aliases, it is not as simple as setting the path when Pathauto is not installed.

Pathauto puts an option to automatically generate the alias on the edit form, and this must be unset in order to set a custom alias.

In this example, the old pages are loaded by node ID, unpublished, and the url alias changed.

$node_storage = \Drupal::entityTypeManager()->getStorage('node');

$old_pages = $node_storage->loadMultiple([
  2199, // My profile
  2200, // My meetings
  2201, // Meetings
  2202, // Subscriptions
  2203, // My subscriptions
  2204, // My transactions
  2205, // Online store
  2206, // Login page
]);

foreach ($old_pages as $page) {
  $page->setUnpublished();

  // Change url.
  $page->path->pathauto = 0;
  $page->path->alias = '/old-portal' . $page->path->alias;
  $page->save();
}
Tags