On WordPress Codex it says that return value (integer) is The new comment's ID.

Any idea how to retrieve comment ID created by wp_insert_comment function?

Thank you.

  • Hi, Welcome to WPSE! What do you mean? You just said that the function returns the ID of created comment. – Jack Johansson Jun 13 '17 at 9:34
  • I would like to echo that ID, but I dont know how. – user2127403 Jun 13 '17 at 9:37

wp_insert_comment is both a hook and a function. Once a comment is left on your blog, this action hook will be triggered, allowing you to modify the comment.

A very simple example would be:


function my_function($comment_id, $comment_object) {
    // Now you have access to $comment_id, save it, print it, do whatever you want with it

If you attempt and add a comment by using wp_insert_comment, then this function will return the ID of the inserted comment after it's done:

function add_new_comment($input, $post_id, $author, $user_id){
    // Get the current time 
    $time = current_time('mysql');
    // Set the arguments
    $data = array(
        'comment_post_ID' => $post_id,
        'comment_author' => $author,
        'comment_author_email' => 'admin@admin.com',
        'comment_author_url' => 'URL HERE',
        'comment_content' => $input,
        'comment_type' => '',
        'comment_parent' => 0,
        'user_id' => $user_id,
        'comment_author_IP' => 'IP HERE',
        'comment_agent' => 'USER AGENT HERE',
        'comment_date' => $time,
        'comment_approved' => 1,
    // Store the ID in a variable
    $id = wp_insert_comment($data);
    // Return the ID
    return $id;

Now, if you call the add_new_comment() like the following, it will add a new comment and return its ID:

echo add_new_comment('My First Commnent', '123' , 'Admin' , '1');

Which is what you are looking for.

  • @user2127403 You're welcome mate. – Jack Johansson Jun 13 '17 at 10:37
  • You can achieve it without creating a function as well. Like: $commentid = wp_insert_comment($data); echo $commentid ; – Jiten Gaikwad Jun 13 '17 at 11:18
  • @JitenGaikwad True. But how do you control the task if not wrapped in function? It will run every time the page is accessed. – Jack Johansson Jun 13 '17 at 11:21
  • @JackJohansson Correct. But it depends on where and how its used on page. If its going to use single time and need to access on page every time we can use without function. If we need to use it at different places and in certain conditions we can use function to avoid code rewriting. – Jiten Gaikwad Jun 13 '17 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.