Create nodes programmatically

Tutorial Goal

Lesson Goal:

Implementation Method

D7

D8

custom function

custom function

D7 Code

The following code snippet can be used wherever there is a requirement to add a new node. Please replace the bold text with actual value.

global $user;
  $node = new stdClass();
  $node->title = "YOUR TITLE";
  $node->type = "YOUR_NODE_TYPE";
  node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->uid = $user->uid; 
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Node with nid " . $node->nid . " saved!\n");

D8 Code

The following code snippet can be used wherever there is a requirement to add a new node. Please replace the bold text with actual value.

use Drupal\node\Entity\Node;

$node = Node::create(['type' => 'YOUR_NODE_TYPE']);
$node->set('title', 'YOUR_TITLE');

//Body can now be an array with a value and a format.
//If body field exists.
$body = [
'value' => 'YOUR_BODY_TEXT', 
'format' => 'basic_html',
];
$node->set('body', $body);
$node->set('uid', YOUR_UID);
$node->status = 1;
$node->enforceIsNew();
$node->save();
drupal_set_message( "Node with nid " . $node->id() . " saved!\n");

Gist Link

https://gist.github.com/gargsuchi/863a556c732b6fab89c99f0bdaa4d2f1

Contact supportStill need assistance? Contact Acquia Support