Skip to main content

Drupal 8-9:How to create a node or taxonomy term programmatically and set alias

Creating Nodes is like creating other entities in Drupal 8. When you have Pathauto installed (token is required as a dependency), you can also create a custom alias and pass a flag for Pathauto so it does not overwrite it with current set of rules.

This is how to programmatically create nodes that must have a strict URL that doesn't match the Pathauto patterns.

    use Drupal\node\Entity\Node;
    use Drupal\pathauto\PathautoState;
    use Drupal\taxonomy\Entity\Term;

      'uid' => 1,
      'title' => 'Test Node Article',
      'status' => 1,
      'type' => 'article',
      'body' => [
        'value' => 'Test article with a custom alias',
        'format' => 'full_html',
      'path' => [
        'alias' => '/test-custom-alias',
        'pathauto' => PathautoState::SKIP,

  // Create the taxonomy term.
  $new_term = Term::create([
    'name' => $term_name,
    'vid' => $vocabulary,
    'parent' => $parent,
    'tid' => $tid,
    'path' => [
      'alias' => $path_alias,
      'pathauto' => PathautoState::SKIP,

  // Save the taxonomy term.


custom module php