[Drupal] How to programmatically create a node in Drupal?

| | 1 min read

When you want to dynamically create content from some raw data in Drupal, you might have to create a node programmatically. This comes in handy when you want to use custom forms to collect user input and then create nodes using the the input collected. If you want to know how to programmatically create a node continue reading.

The below code can be added to any of the module files to create a node programmatically.

$node =  new stdClass(); // Initialize a node object
$node->type = 'content_type'; // machine name of created content type.
$node->title = 'node_title'; // Node title
$node->body = 'node_body'; // Node body
$node->promote = 1; // Promote content to front page
$node->status = 1; // Publish the node
$node->uid = $user->uid; // Add the created user id
node_save($node); // Save the node

If the above code is added correctly, new node will be created and saved according to your requirement.