WordPress at a glance

add_comment_meta() WP 2.9.0

Adds metadata (custom field) for the specified comment.

You can use update_comment_meta() to add such metadata. Often it is more convenient and works universally, updates the field or creates a new one if there is no field yet.

This function must be used when we need to add several meta fields with the same names (key). To do this, the function has $unique parameter, which is false by default - it means that not unique key is created by default - this means that there can be several fields with this name.

Works based on: add_metadata()

No Hooks.

Return

Int/true/false. Meta ID on success, false on failure.

Usage

add_comment_meta( $comment_id, $meta_key, $meta_value, $unique );
$comment_id(int) (required)
Comment ID to which we nedd to add meta field.
$meta_key(string) (required)
Meta field name.
$meta_value(mixed) (required)
Meta field value.
$unique(true/false)
Whether the same key should not be added.
Do you want to make this field unique or not? If set to true, WordPress will first check if there is already field with the same key, and if there is, the field will not be added.
Default: false

Examples

#1 Add metadata to each new comment

Let's say we need to add a meta field to the comment when it is published (to the new comment). To do it, we use the comment_post hook which is triggered when a comment is published.

add_action( 'comment_post', 'add_comment_metadata_field' );
function add_comment_metadata_field( $comment_id ) {
   add_comment_meta( $comment_id, 'my_metadata_key', $_POST['my_metadata_value'] );
}

#2 More examples

See the description of add_post_meta(). add_comment_meta() works similarly, only here it is necessary to specify the ID of the comment, but not post ID. The rest is exactly the same...

Code of add_comment_meta: wp-includes/comment.php VER 4.9.8

<?php
function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
	$added = add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
	if ( $added ) {
		wp_cache_set( 'last_changed', microtime(), 'comment' );
	}
	return $added;
}

Related Functions

From tag: Metadatas (any)

No comments
    Hello, !     Log In . Register