How to Create Node Comments in Drupal Programmatically

Creating node comments or replies to comments in Drupal programmatically can be done by using the built in API function named "comment_form_submit". The following help file will show you how to do this. This was tested in Drupal version 6, but should work in Drupal 5.

Begin by loading the Drupal environment like we always do. If your writing a module, you don't need this part.

<?php//Load and init the Drupal Systemrequire_once 'includes/';drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);?>

Then load the comment module libraries. If your writing a module, you don't need this part either.


If you want to assign these comments to a specific user, you'll need to setup the global user variable by loading the user account as shown. In this example, we are using the admin user.

<?phpglobal $user;$user user_load(array(uid => 1));?>

Like other items we create in Drupal, we need to create the form state with fields and values. The following fields are all you need to properly create a comment.

The "author" field tells Drupal which user to assign this comment to. The "subject" and "comment" fields are self explanatory. The "op" fields is set to "save", and finally, you use the "nid" field to tell Drupal which node this comment is assigned to.

In this example, We are creating this comment on node 65.

<?php$forum_comment_fields = array();$forum_comment_fields['values']['author'] = $user->name;$forum_comment_fields['values']['subject'] = "Test Comment";$forum_comment_fields['values']['comment'] = 'Test';$forum_comment_fields['values']['op'] = t('Save');$forum_comment_fields['values']['nid'] = 65;?>

To create the comment, go ahead and execute the function "comment_form_submit". The first field must always be "comment_form", the second field is your form state variable. Then print out any error or status messages.

<?php comment_form_submit("comment_form"$forum_comment_fields);print_r(drupal_get_messages());?>

Lets say you want to create a comment to a comment, aka a reply. It's the same exact procedure, except you add an additional field to to the form state named "pid", parent comment ID.

<?php$forum_comment_fields = array();$forum_comment_fields['values']['author'] = $user->name;$forum_comment_fields['values']['subject'] = "Test3";$forum_comment_fields['values']['comment'] = 'Test1';$forum_comment_fields['values']['nid'] = 65;$forum_comment_fields['values']['pid'] = 6;$forum_comment_fields['values']['op'] = t('Save');comment_form_submit("comment_form"$forum_comment_fields);print_r(drupal_get_messages());?>