使用 Drupal API 通过代码方式添加新评论

使用以下代码可以实现向 Drupal 中添加新评论

<?php

// 以下代码中用到的 $values 变量包含了 comment 和 nid 等内容,用于设置评论标题及所属节点
// 实际开发中只需要正确设置相应的值即可

global $user;

$comment = (object) array(
  'name' => '',
  'mail' => '',
  'homepage' => '',
  'subject' => drupal_substr($values['comment'], 0, 20),
  'comment_body' => array(
    LANGUAGE_NONE => array(
      array(
        'value' => $values['comment'],
        'format' => 'plain_text'  // 输入格式名称
      ),
    )
  ),
  'cid' => NULL,
  'pid' => NULL,  // 父评论cid,如果发布的评论是回复另一条评论,可以在这里设置
  'language' => LANGUAGE_NONE,
  'uid' => $user->uid,
  
  'nid' => $values['nid'],
);

comment_save($comment);