[Drupal] How to get the nid from a newly added node using node_save()?

| | 1 min read

If you are a Drupal Developer you will often encounter situations where you have to use the node_save() function to add a new node to your Drupal site. Drupal does not need you to specify the nid in the standard node object. However there will be situations where you need the nid of the saved node for performing additional operations. If you are looking to know how to get the nid from a newly added node using node_save() then read on.

The solution is very simple. Drupal stores the nid in the standard node class after node_save() is called. This means that the nid will be available in the standard node class after you have called the node_save() function. If $node is your object used to add a new node then nid will be available as $node->nid. This is due to a very simple reason. In PHP the objects are always passed by reference and not passed by value.

Hope you have found this article on the Drupal node_save() function useful. If you have any queries regarding the content of this article, use the comment form below.

References:

  1. http://drupal.org