Skip to content

Instantly share code, notes, and snippets.

@ccamara
Last active January 3, 2016 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccamara/8397040 to your computer and use it in GitHub Desktop.
Save ccamara/8397040 to your computer and use it in GitHub Desktop.
Programatically creation of nodes in #Drupal7
<?php
/**
* Creates 'nodetype' pages.
*
* @param array $content
* Assoc array with machine names as key and node title.
*/
function yourmodule_create_nodetype($content) {
foreach ($content as $machine_name => $content_item) {
$node = new stdClass();
$node->title = $content_item;
$node->type = 'nodetype'; //replace nodetype with desired node type's machine name.
node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
$node->language = 'en'; // Replace with language prefix.
$node->uid = 1; // Select uid to be node's author.
$node->status = 1; // Whether it's published or not.
$node->promote = 0; // Whether it's promoted to frontpage or not.
$node->comment = 0; // Whether allows comments or not.
// Uncomment below if using module machine_name
// $node->field_machine_name[LANGUAGE_NONE][]['value'] = $machine_name;
node_save($node);
if (! empty($node->nid)) {
drupal_set_message(t('Inserted node !name', array('!name' => $content_item)));
}
}
}
<?php
/**
* Creates a node using previously created function from a different module
*/
yourmodule_create_nodetype(array(
'machine_name' => 'Node title',
'machine_name2' => 'Node title 2',
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment