I’m trying to add a simple custom comment management facility to a WordPress site. The comment form is managed by javascript and works fine, including calling into my PHP file as needed. I’m trying to utilize wp_insert_comment. Based on the Example code there, I believe I’m assembling the right $commentdata array as argument. Here’s my code, including some simple logging to verify the data:
<?php
/*
include '../../../wp-includes/comment.php';
include ‘<MY PATH>/wp-includes/comment.php';
*/
$db = new mysqli($hostname,$username,$password,$database);
if ($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
/* Open Log file */
$filename=“<MY PATH>/wp-content/themes/blocks2/dbi/testf.log";
$fd = fopen($filename, "a");
$str = "++++--------new_post---------++++";
fwrite($fd, $str . "\n");
$cid = 0;
$pid = $_POST['pid'];
$ulogin = $_POST['ulogin'];
$uid = $_POST['uid'];
$cmttxt = $_POST['txt'];
$str = $ulogin . ' ' . $cmttxt;
fwrite($fd, $str . "\n");
$commentdata = array(
'comment_post_ID' => $pid,
'comment_author' => $ulogin,
'comment_author_email' => 'someone@example.com', //fixed value - can be dynamic
'comment_author_url' => 'http://example.com', //fixed value - can be dynamic
'comment_content' => $cmttxt,
'comment_type' => '', //empty for regular comments, 'pingback' for pingbacks, 'trackback' for trackbacks
'comment_parent' => 0, //0 if not a reply to another comment; if it's a reply, parent comment ID here
'user_id' => $uid
);
$str=">>>comment_post_ID=" . $commentdata["comment_post_ID"] . " comment_author=" . $commentdata["comment_author"] . " comment_author_email=" . $commentdata["comment_author_email"] . " comment_author_url=" . $commentdata["comment_author_url"] . " comment_content=" . $commentdata["comment_content"] . " comment_type=" . $commentdata["comment_type"] . "| comment_parent=" . $commentdata["comment_parent"] . " user_id=" . $commentdata["user_id"];
fwrite($fd, $str . "\n");
/* Insert new comment and get the comment ID */
$comment_id = wp_new_comment( $commentdata );
$str = "AFTER wp_new_comment-comment_id= " . $comment_id;
fwrite($fd, $str . "\n");
fclose($fd);
For a comment with text = “Silly-Comment”, here is what is logged:
ken Silly-Comment
>>>comment_post_ID=17 comment_author=ken comment_author_email=someone@example.com comment_author_url=http://example.com comment_content=Silly-Comment comment_type=| comment_parent=0 user_id=3
The final log entry "AFTER wp_new_comment-comment_id= " . $comment_id; is missing.
It’s occurred to me that I might need to explicitly include wp-includes/comment.php, which contains wp_new_comment. I’ve attempted the two versions of the includes shown commented-out at the top of the code, but neither seems to have any effect.
Can anyone supply some guidance please?
Thanks in advance,
Ken Bowen