Processes the submission of a comment. It is called in the file wp-comments-post.php when a comment is submitted through the comment form.
The function processes the provided data and adds the comment to the database or returns WP_Error.
Unlike wp_new_comment(), this function expects data without escaped slashes - i.e., the $_POST data needs to be processed with the function wp_unslash().
The function is convenient to use instead of wp_new_comment() to avoid writing unnecessary checks such as:
whether there is a post for which the comment is being published;
whether the user has the right to read the post;
whether commenting is open;
whether the commented post is in the trash;
whether the commented post is password protected;
and other checks that a comment goes through during standard commenting in WordPress.
WP_Comment|WP_Error. Comment object if the comment was successfully recorded or error object.
Usage
wp_handle_comment_submission( $comment_data );
$comment_data(array) (required)
Data of the comment as an array. You can only pass the following data:
comment_post_ID — (string|int) ID of the post to which the comment relates.
author — (string) Name of the comment author.
email — (string) email of the commenter.
url — (string) URL of the commenter.
comment — (string) Text of the comment.
comment_parent — (string|int) ID of the parent comment. Default: 0.
_wp_unfiltered_html_comment — (string) Nonce value to allow unfiltered HTML in the text.
If you need to pass additional data, then use the function wp_new_comment() separately.
Examples
#1 Add a comment via AJAX
Suppose we publish a comment that contains standard fields and meta-fields and we do it through AJAX, but not through the wp-comments-post.php file.
In this case, to not write additional code for checks, it is more convenient to use this function. Use the following code in the AJAX request handler function:
add_action( 'wp_ajax_myaddcomment', 'myaddcomment_handler' );
function myaddcomment_handler() {
// try to write the comment to the database
$comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
// error when adding a comment
if( is_wp_error( $comment ) ){
wp_send_json_error( $comment->get_error_message() );
}
// comment added - all OK!
// process additional fields
$foo = (int) $_POST['foo'];
$bar = (int) $_POST['bar'];
if( $foo ){
update_comment_meta( $comment->comment_ID, 'foo', $foo );
}
if( $bar ){
update_comment_meta( $comment->comment_ID, 'bar', $bar );
}
// return the result
wp_send_json_success( $comment );
}