2

Since WordPress 4.4, it seems like it is no longer possible to use get_the_ID() or the_ID() when hooking onto the comment_post action.

How can I get the post_id when a new comment is saved?

  • 1
    for now this is the only solution I've found: $comment = get_comment($comment_id); $post_id = $comment->comment_post_ID; – Dudo1985 Dec 10 '15 at 9:29
3

The third parameter, $commentdata can be used to get the ID for the post that the comment was made on:

function wpse211367_comment( $comment_ID, $comment_approved, $commentdata ) {
    // The id for the post that the comment is related to is available
    // in the $commentdata array:
    $comment_post_id = $commentdata['comment_post_ID'];
}
add_action( 'comment_post', 'wpse211367_comment', 10, 3 );

The $commentdata array:

Array
(
    [comment_post_ID] => 149
    [comment_author] => dave
    [comment_author_email] => email@domain.com
    [comment_author_url] => 
    [comment_content] => All work and no play makes Dave a dull boy.
    [comment_type] => 
    [comment_parent] => 0
    [user_ID] => 1
    [user_id] => 1
    [comment_author_IP] => ::1
    [comment_agent] => Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
    [comment_date] => 2016-09-23 03:13:40
    [comment_date_gmt] => 2016-09-23 03:13:40
    [filtered] => 1
    [comment_approved] => 1
)

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.