From 4da03f3cfcc0f63347eaa23d49ccd748073046b5 Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Fri, 25 Sep 2015 04:40:30 +0000 Subject: [PATCH] Allow metadata to be attached to comment at time of creation. The new `$comment_meta` parameter of `wp_insert_comment()` allows an array of key/value pairs to be passed when creating a comment. These pairs are then stored as commentmeta when the comment has been created. Props tellyworth, wonderboymusic. Fixes #12431. git-svn-id: https://develop.svn.wordpress.org/trunk@34533 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/comment-functions.php | 10 ++++++++++ tests/phpunit/tests/comment.php | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/wp-includes/comment-functions.php b/src/wp-includes/comment-functions.php index 7b76dbedeb..ad8f9c2fa3 100644 --- a/src/wp-includes/comment-functions.php +++ b/src/wp-includes/comment-functions.php @@ -1377,6 +1377,7 @@ function wp_get_current_commenter() { * Inserts a comment into the database. * * @since 2.0.0 + * @since 4.4.0 Introduced `$comment_meta` argument. * * @global wpdb $wpdb WordPress database abstraction object. * @@ -1401,6 +1402,8 @@ function wp_get_current_commenter() { * @type int $comment_post_ID ID of the post that relates to the comment, if any. * Default empty. * @type string $comment_type Comment type. Default empty. + * @type array $comment_meta Optional. Array of key/value pairs to be stored in commentmeta for the + * new comment. * @type int $user_id ID of the user who submitted the comment. Default 0. * } * @return int|false The new comment's ID on success, false on failure. @@ -1439,6 +1442,13 @@ function wp_insert_comment( $commentdata ) { } $comment = get_comment( $id ); + // If metadata is provided, store it. + if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) { + foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) { + add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true ); + } + } + /** * Fires immediately after a comment is inserted into the database. * diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index a20f58d5ab..4c69ccac49 100644 --- a/tests/phpunit/tests/comment.php +++ b/tests/phpunit/tests/comment.php @@ -273,4 +273,19 @@ class Tests_Comment extends WP_UnitTestCase { $sent = wp_new_comment_notify_postauthor( $c ); $this->assertFalse( $sent ); } + + /** + * @ticket 12431 + */ + public function test_wp_new_comment_with_meta() { + $c = $this->factory->comment->create( array( + 'comment_approved' => '1', + 'comment_meta' => array( + 'food' => 'taco', + 'sauce' => 'fire' + ) + ) ); + + $this->assertEquals( 'fire', get_comment_meta( $c, 'sauce', true ) ); + } }