wp_insert_comment()
Inserts/adds a comment into the database.
IMPORTANT! This function is expecting escaped data to be passed to it! It means that if we pass custom data (data not from the $_POST request), we need to sanitize the data with wp_slash() before passing it to this function.
Consider using wp_new_comment(), which automatically sanitizes and validates the comment data before calling this function to insert the comment into the database.
Hooks from the function
Return
Int|false
. The new comment's ID on success, false on failure.
Usage
wp_insert_comment( $commentdata );
- $commentdata(array) (required)
Array of arguments for inserting a new comment.
-
comment_agent(string)
The HTTP user agent of the $comment_author when the comment was submitted.
Default: '' -
comment_approved(int|string)
Whether the comment has been approved.
Default: 1 -
comment_author(string)
The name of the author of the comment.
Default: '' -
comment_author_email(string)
The email address of the $comment_author.
Default: '' -
comment_author_IP(string)
The IP address of the $comment_author.
Default: '' -
comment_author_url(string)
The URL address of the $comment_author.
Default: '' -
comment_content(string)
The content of the comment.
Default: '' -
comment_date(string)
The date the comment was submitted. To set the date manually, $comment_date_gmt must also be specified.
Default: current time -
comment_date_gmt(string)
The date the comment was submitted in the GMT timezone.
Default: $comment_date in the site's GMT timezone -
comment_karma(int)
The karma of the comment. -
comment_parent(int)
ID of this comment's parent, if any. -
comment_post_ID(int)
ID of the post that relates to the comment, if any. -
comment_type(string)
Comment type.
Default: 'comment' -
comment_meta(array)
Optional. Array of key/value pairs to be stored in commentmeta for the new comment. - user_id(int)
ID of the user who submitted the comment.
-
Examples
#1 Add new custom comment
$data = [ 'comment_post_ID' => 1, 'comment_author' => 'admin', 'comment_author_email' => '[email protected]', 'comment_author_url' => 'http://', 'comment_content' => 'content here', 'comment_type' => '', 'comment_parent' => 0, 'user_id' => 1, 'comment_author_IP' => '127.0.0.1', 'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)', 'comment_date' => null, // current_time('mysql') 'comment_approved' => 1, ]; wp_insert_comment( wp_slash($data) );
Notes
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 2.0.0 | Introduced. |
Since 4.4.0 | Introduced the $comment_meta argument. |
Since 5.5.0 | Default value for $comment_type argument changed to comment. |