Set generate automatic URL alias programmatically

Created on 24 April 2017, about 7 years ago
Updated 13 May 2017, about 7 years ago

With pathauto enabled, how can we programmatically set “Generate automatic URL alias” to TRUE for existing nodes, using PHP or SQL?

I have tried all patches and PHP or SQL solutions suggested and nothing has worked for the latest D8 + pathauto releases.

After having studied various options, I believe this could be the fastest way to do it:

use Drupal\node\Entity\Node;

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'my_content_type');
$entity_ids = $query->execute();

foreach ($entity_ids AS $nid) {

$node = Node::load($nid);
$node->set("path", ["pathauto" => TRUE]);	//this line is not doing anything
$node->save();
}

No errors but when I check my nodes after the execution of this code, they still have the "Generate automatic URL alias" disabled/invisible.

💬 Support request
Status

Fixed

Component

Code

Created by

🇬🇧United Kingdom David Fiaty

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇮🇳India TOMY MOHAN

    use Drupal\pathauto\PathautoState;
    $contentTypes = [ 'library', 'news', 'events'];
    foreach ($contentTypes as $contentType) {
    $nodeQuery = \Drupal::entityQuery('node');
    $nodeQuery->condition('type', $contentType);
    $entity_ids = $nodeQuery->execute();
    if (isset($entity_ids) && !empty($entity_ids)) {
    foreach ($entity_ids AS $entity_id) {
    $node = Node::load($entity_id);
    $node->path->pathauto = PathautoState::CREATE;
    $node->save();
    }
    }
    }

Production build 0.69.0 2024