0
votes

I have a really simple piece of PHP code on my WP functions.php file, it creates a new comment:

    $time = current_time('mysql');

    $com_meta = array(
        "img_id" => $attach_id,
    );
    // $attach_id holds the ID of an image I want to attach to the comment in comment_meta

    $data = array(
        'comment_post_ID'        => 2819,
        'comment_author'         => 'My test title',
        'comment_author_email'   => '[email protected]',
        'comment_content'        => 'Test comment message.',
        'comment_type'           => '',
        'comment_date'           => $time,
        'comment_approved'       => 0,
        'comment_meta'           => $com_meta,
    );

    $comm_id = wp_insert_comment( $data );

    die( 'comment created, comment id: ' . $comm_id );

There are no PHP errors, and the comment is created just fine. All the other data like "My test title" is there as expected. Only the comment_meta field is missing completely. In the $comment object, there is not even an empty comment_meta present.

What could I be missing?

This is what the $comment object looks like:

WP_Comment Object ( [comment_ID] => 9 [comment_post_ID] => 2819 [comment_author] => My test title [comment_author_email] => [email protected] [comment_author_url] => [comment_author_IP] => [comment_date] => 2019-10-18 13:33:03 [comment_date_gmt] => 2019-10-18 10:33:03 [comment_content] => Test comment message. [comment_karma] => 0 [comment_approved] => 0 [comment_agent] => [comment_type] => [comment_parent] => 0 [user_id] => 0 [children:protected] => [populated_children:protected] => [post_fields:protected] => Array ( [0] => post_author [1] => post_date [2] => post_date_gmt [3] => post_content [4] => post_title [5] => post_excerpt [6] => post_status [7] => comment_status [8] => ping_status [9] => post_name [10] => to_ping [11] => pinged [12] => post_modified [13] => post_modified_gmt [14] => post_content_filtered [15] => post_parent [16] => guid [17] => menu_order [18] => post_type [19] => post_mime_type [20] => comment_count ) )

2
Hardcore typo in the headline: I'm using wp_insert_comment(), not add_comment_meta() here. - Jussi

2 Answers

0
votes

I found the answer.

The answer is, that the comment_meta is not supposed to be part of the standard $comment object at all.

The comment_meta is there, but you need to access it with get_comment_meta().

0
votes

This data is filled with an array to be used later or called after the information saved as comment_id: 'comment_meta' (array) Optional. Array of key/value pairs to be stored in commentmeta for the new comment.

 $com_meta = array(
            "comment_id" => $comment_id,
            "meta_key" => "img_id",
           "meta_value" => "250",
    );

There is no need to insert the key comment_id, it will be inserted automatically by wordpress