Create a node programmatically with Entity Metadata Wrapper

Public

There is several code snippets on Dropbucket to create a Node using core Drupal functions. So here is a new approach using Entity Metadata Wrapper, this function can take a parameter to request for an immediate save of the new Entity (the Node) or return the Wrapper to be able to work a bit more on it in the code before saving it.

N.B.: Entity Metadata Wrapper is a part of the Entity API, so make sure to enable it

</> CopyGet raw version
php
  1. /**
  2.  * Helper function to create a new node
  3.  * @param string $type Target content type
  4.  * @param bool $save Should we save the entity after creation? It can be
  5.  * save out of the function.
  6.  * @return obj If the entity is saved, ($save = TRUE) return the
  7.  * entity object, else return the wrapper.
  8.  *
  9.  * source: https://www.drupal.org/node/1388922
  10.  */
  11. function _my_module_create_node($type = 'page', $title = 'default_title', $save = TRUE) {
  12. global $user;
  13.  
  14. $values = array(
  15. 'type' => $type,
  16. 'uid' => $user->uid,
  17. 'status' => 1,
  18. 'comment' => 0,
  19. 'promote' => 0,
  20. );
  21. $entity = entity_create('node', $values);
  22.  
  23. $ewrapper = entity_metadata_wrapper('node', $entity);
  24. $ewrapper->language->set('en');
  25.  
  26. $ewrapper->title->set($title);
  27. $ewrapper->revision->set(1);
  28.  
  29. // Now just save the wrapper and the entity
  30. // There is some suggestion that the 'true' argument is necessary to
  31. // the entity save method to circumvent a bug in Entity API. If there is
  32. // such a bug, it almost certainly will get fixed, so make sure to check.
  33. if ($save) {
  34. $ewrapper->save();
  35. return $entity;
  36. }
  37. else {
  38. return $ewrapper;
  39. }
  40. }